此程序(与选项-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的问题吗?
我知道GCC / libc ++中的短字符串优化,但是短字符串的2000个字符不是太多吗?这完全是SSO的问题吗?
用std::string
2000
s呼叫char
:
std::string str(2000, 'x');
并不意味着必须为new
对象实例外部所需的任何内存调用std::string
。 std::string
如何管理其内存SSO或其他方式完全取决于实现。