使用 MINGW gcc 编译时,不会为 std::string 调用重载的新运算符
When compiling with MINGW gcc, overloaded new operator is not called for std::string
此程序(使用选项 -std=c++17
编译)
#include <stdio.h>
#include <string>
void* operator new(std::size_t nrOfBytes) {
printf("allocate %zd 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;
delete i;
// new operator is not called when compiled with GCC
// but is called with Clang and MSVS
std::string str(2000, 'x');
return 0;
}
使用 Clang 或 MSVS 编译时,打印:
allocate 4 bytes on heap
allocate 2016 bytes on heap
然而,当使用 GCC(MSYS 在 Windows 上提供的版本 9.2.0)编译时,它只打印:
allocate 4 bytes on heap
我知道 GCC/libc++ 中的短字符串优化,但是 2000 个字符对于短字符串来说不是太多了吗?这完全是 SSO 的问题吗?
此程序(使用选项 -std=c++17
编译)
#include <stdio.h>
#include <string>
void* operator new(std::size_t nrOfBytes) {
printf("allocate %zd 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;
delete i;
// new operator is not called when compiled with GCC
// but is called with Clang and MSVS
std::string str(2000, 'x');
return 0;
}
使用 Clang 或 MSVS 编译时,打印:
allocate 4 bytes on heap
allocate 2016 bytes on heap
然而,当使用 GCC(MSYS 在 Windows 上提供的版本 9.2.0)编译时,它只打印:
allocate 4 bytes on heap
我知道 GCC/libc++ 中的短字符串优化,但是 2000 个字符对于短字符串来说不是太多了吗?这完全是 SSO 的问题吗?