Chris Theis wrote:
....
Hi Gianni,
could you please elaborate on the "may or may not" part. If I understand you
correctly you indicate that due to the use of malloc inside ones own
implementation of new it is not for sure that the object is constructed. In
my experience the following code worked just fine also for objects, but I
don't wanna claim to be an export on implementations of memory allocators.
void* operator new(size_t Bytes, const char* pFile , int Line )
{
return CMemObserver::GetRef().Allocate( Bytes, pFile, Line );
};
void* CMemObserver::Allocate( size_t Bytes, const char* pFile, int Line ) {
void* pPtr = malloc( Bytes);
if( !pPtr )
throw std::bad_alloc(); // ANSI/ISO compliant behavior
m_MemoryMap[pPtr] = CNewData( pFile, Line);
return pPtr;
}
Any further insight or hints for improvements are more than welcome.
"may or may noy" refers to how some compiler implementations define
opertor new to have a "caching" behaviour. Have a look at the regular
new operator for the latest GCC C++ compiler - if you have libraries
that use this allocator, defining your own allocator will not change the
allocator in the library.
Also, if a class defined it's own new operator, your global new operator
will not be used.
Hence, I think the best way to gets stats on object level memory
allocation is implementation dependant, in GCC for example, the best
mechanism is to substitute malloc/free etc and to set the magic
environment variable GLIBCXX_FORCE_NEW (or GLIBCPP_FORCE_NEW depending
on version).
See:
http://gcc.gnu.org/onlinedocs/libstd...t/howto.html#3
The solution you propose is fine if you only care about the classes in
modules you have control over and you need to be careful that the
allocation of an object uses the corresponding deallocator for
destruction. This is not allways true when you have "standard" objects
being allocated and deallocated in different modules. "namespaces" may
come to the rescue here, I'm not sure but it seems likely that an
"global" new operator defined in a namespace will only apply to classes
in that namespace.
However, if you're looking at leak detection or "stats", usually you're
looking for results from the entire application hence finding a way to
trap all dynamic construction events is the ultimate goal. The nice
thing about trapping malloc/free is that it also traps regular C
libraries as well and hence mixed C/C++ applications are also caught.