Search code examples
c++stdvectornullptr

Does std::vector::pop_back set the pointers of the objects in it to nullptr?


Does std::vector::pop_back set the pointers of the objects in it to nullptr or does it just delete the objects?

I see that the size of my vector decreases so the object is obviously deleted but I want to know whether the pointers are set to nullptr or do I have to do that manually?

Edit: I asked this question in according to a vector containing pointers. Example: vector<Bitmap*>.


Solution

  • Logically, the 'destructor' of the object popped is called. Note however that for an integral type (and a pointer is an integral type), the 'destructor' is a no-op.

    What this means is:

    Here Thing::~Thing() will be called:

    std::vector<Thing> things;
    things.emplace_back({});
    things.pop_back();
    

    Here nothing will be called and you will have a resource leak

    std::vector<Thing*> things;
    things.emplace_back(new Thing{});
    things.pop_back();
    

    Here std::unique_ptr<Thing>::~std::unique_ptr<Thing>() will be called and you will not have a resource leak

    std::vector<std::unique_ptr<Thing>> things;
    things.emplace_back(std::make_unique<Thing>());
    things.pop_back();