Julian Declercq
Julian Declercq

Reputation: 1596

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*>.

Upvotes: 1

Views: 5165

Answers (3)

R Sahu
R Sahu

Reputation: 206567

From http://en.cppreference.com/w/cpp/container/vector/pop_back

void pop_back();

Removes the last element of the container.
Calling pop_back on an empty container is undefined.
No iterators or references except for back() and end() are invalidated.

I wouldn't assume or extrapolate anything beyond that.

Upvotes: 0

ARLabs
ARLabs

Reputation: 1524

http://www.cplusplus.com/reference/vector/vector/pop_back/

The end iterator and any iterator, pointer and reference referring to the removed element are invalidated. Iterators, pointers and references referring to other elements that have not been removed are guaranteed to keep referring to the same elements they were referring to before the call.

If your vector contains directly objects, the destructor of the object is called. Obviously if you are using a vector of pointer (with ownership) you MUST call delete yourself.

std::vector<P*> myvector;
...
delete myvector.back();
myvector.pop_back();

Upvotes: 4

Richard Hodges
Richard Hodges

Reputation: 69864

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();

Upvotes: 6

Related Questions