使用gcc编译时,不会为std :: string调用重载的new运算符

问题描述 投票:1回答:1

此程序(与选项-std = c ++ 17一起编译)

#include <stdio.h>
#include <string>
void* operator new(std::size_t nrOfBytes) {
    printf("allocate %d bytes on heap\n", nrOfBytes);
    void* p = malloc(nrOfBytes);
    if (p) {
        return p;
    } else {
       throw std::bad_alloc{};
    }
}
int main() {
    // new operator is called when compiled with Clang or MSVS or GCC 
    int* i = new int;
    // new operator is not called when compiled with GCC
    // but is called with Clang and MSVS 
    std::string str(2000, 'x');
    return 0;
}

打印

在堆上分配4个字节

在堆上分配2016个字节

当使用Clang或MSVS编译时。但是,当使用GCC(Windows上的MSYS提供的9.2.0版本)进行编译时,它仅打印

在堆上分配4个字节

我知道GCC / libc ++中的短字符串优化,但是短字符串的2000个字符不是太多吗?这完全是SSO的问题吗?

c++ gcc stdstring gcc9
1个回答
0
投票

我知道GCC / libc ++中的短字符串优化,但是短字符串的2000个字符不是太多吗?这完全是SSO的问题吗?

std::string2000s呼叫char

std::string str(2000, 'x');

并不意味着必须为new对象实例外部所需的任何内存调用std::stringstd::string如何管理其内存SSO或其他方式完全取决于实现。

© www.soinside.com 2019 - 2024. All rights reserved.