简体   繁体   中英

Where are std::list elements allocated?

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.

我认为原因是QList将其元素内部存储在void*指针中,而std::list将使用其分配器来忽略新的操作符覆盖。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM