Jul*_*rcq 1 c++ stdvector nullptr
是否std::vector::pop_back设置它的对象的指针,nullptr或者它只是删除的对象?
我看到我的向量的大小减小了,所以对象显然被删除了,但我想知道指针是设置为nullptr还是必须手动执行?
编辑:我根据包含指针的向量提出了这个问题。例子:vector<Bitmap*>。
从逻辑上讲,弹出对象的“析构函数”被调用。但是请注意,对于整型(指针是整型),“析构函数”是无操作的。
这意味着:
这里Thing::~Thing()将被称为:
std::vector<Thing> things;
things.emplace_back({});
things.pop_back();
Run Code Online (Sandbox Code Playgroud)
这里什么都不会被调用,你将有资源泄漏
std::vector<Thing*> things;
things.emplace_back(new Thing{});
things.pop_back();
Run Code Online (Sandbox Code Playgroud)
这里std::unique_ptr<Thing>::~std::unique_ptr<Thing>()将被调用,你不会有资源泄漏
std::vector<std::unique_ptr<Thing>> things;
things.emplace_back(std::make_unique<Thing>());
things.pop_back();
Run Code Online (Sandbox Code Playgroud)