I'm trying hard to replace the global new and delete operators with XCode 3.2, GCC 4.2, libstdc++ 4.0, dynamic version.
I took the protypes directly from the header "new" and implemented them. They are pasted below.
The project is a .plugin so a dynamic lib. This plug-in MUST delegate allocation to the main application's own alloc/free routines, which are in an old C SDK.
All my own call to new/delete along with std::list and std::map allocations are correctly replaced, BUT not when std::vector::push_back has to grow its buffer. It that case, my operator new is not called but my operator delete is. I know that, because I write a token in the first four bytes of any buffer allocated by my new operator and I check this token in operator delete. See below for offending code.
extern "C++"
{
__attribute__((visibility("default"))) void* operator new(std::size_t) throw (std::bad_alloc);
__attribute__((visibility("default"))) void* operator new[](std::size_t) throw (std::bad_alloc);
__attribute__((visibility("default"))) void operator delete(void*) throw();
__attribute__((visibility("default"))) void operator delete[](void*) throw();
__attribute__((visibility("default"))) void* operator new(std::size_t, const std::nothrow_t&) throw();
__attribute__((visibility("default"))) void* operator new[](std::size_t, const std::nothrow_t&) throw();
__attribute__((visibility("default"))) void operator delete(void*, const std::nothrow_t&) throw();
__attribute__((visibility("default"))) void operator delete[](void*, const std::nothrow_t&) throw();
}
The following code will cause an assert when "yo" goes out of scope because the memory allocated for the std::vector was not allocated by my operator new.
{
std::vector<std::string> yo;
yo.push_back("yoyoma");
yo.push_back("yoyoma");
yo.push_back("yoyoma");
yo.push_back("yoyoma");
}
The following code is ok because std::vector::reserve calls my operator new:
{
std::vector<std::string> yo;
yo.reserve(4);
yo.push_back("yoyoma");
yo.push_back("yoyoma");
yo.push_back("yoyoma");
yo.push_back("yoyoma");
}
GBD (debugger) won't let met step into the std::vector::push_back implementation when it need to grow the buffer (the method is named _M_insert_aux). All I know is that my operator new is never called from std::vector::push_back.
The workaround above can't be applied to all the 3rd party libs that I'm using. One of which is a big user of push_back.
I tried linking statically to libstdc++.a but I'm having the same issue.
Is there some specialization for std::vector< std::string > that doesn't use the global new operator?
BTW this worked perfectly on windows with VS9.