简体   繁体   中英

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

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

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

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.

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