I am playing around with std::list to understand how it stores elements. I have written the following code to check where the elements are allocated.
#include <QtCore>
#include <list>
class Dummy
{
public:
Dummy(int i) : _i(i){qDebug() << _i << " created";}
Dummy(const Dummy& copy) : _i(copy._i) {qDebug() << _i << " copied";}
~Dummy() {qDebug() << _i << " destructed";}
void* operator new (std::size_t size)
{
qDebug() << "Object newed";
return ::operator new(size);
}
void* operator new (std::size_t size, void* ptr)
{
qDebug() << "Object newed 2";
return ::operator new(size, ptr);
}
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value)
{
qDebug() << "Object newed 3";
return ::operator new(size, nothrow_value);
}
void* operator new[](std::size_t size)
{
qDebug() << "Object array newed";
return ::operator new[](size);
}
void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_value)
{
qDebug() << "Object array newed 2";
return ::operator new[](size, nothrow_value);
}
void* operator new[] (std::size_t size, void* ptr)
{
qDebug() << "Object array newed 3";
return ::operator new[](size, ptr);
}
void operator delete(void* dptr)
{
qDebug() << "Object deleted";
::operator delete(dptr);
}
void operator delete[](void* dptr)
{
qDebug() << "Object array deleted";
::operator delete[](dptr);
}
int _i;
};
int main(int argc, char *argv[])
{
std::list<Dummy> lstEntries;
lstEntries.push_back(Dummy(1));
lstEntries.push_back(Dummy(2));
std::list<Dummy> newList;
lstEntries = newList;
return 0;
}
None of my operator new overrides are getting called when I insert elements into the list. Why is that? Doesn't the list allocate it's elements in the heap? Or have I missed the correct new operator which the list uses to allocate objects?
If I use a QList (Qt) instead of std::list, void* operator new (std::size_t size) gets called. Looks like QList allocates it's elements in heap.
I think the reason is that QList
stores its elements internally in a void*
pointer, whereas std::list
will use its allocator for all this disregarding your new operator override.