如何检查 std::unique_ptr 是否为空,如果它在 std::vector 中?

How to check if a std::unique_ptr is null, if it is in a std::vector?

我有一个 vector<unique_ptr<BaseClass>>,我正在通过调用 vec.push_back(std::make_unique<DerivedClass>()) 向它添加新项目。

如何使用 operator bool() 检查 nullptr

我试过直接使用vec.back(),像这样:

if((!vec.empty() && vec.back())
{
  // yay!
}
else
{
  //nay!
}

但无论指针的内容如何,​​它总是 returns 为 false。

您可以从 here, if the vector is empty, it's UB. If it's not your case, as you can read from here instead 中了解到,unique_ptr 有一个 operator bool() 检查 对象当前是否由 unique_ptr

所以,与:

vector.empty();

您可以检查向量是否有元素,并使用:

vector<unique_ptr<something>> vec;
vec.push_back(make_unique<something>());
if(vec.front()){ // example
    // do something
}

你检查第一个 unique_ptr 是否指向一个对象。

PS:如果你总是使用vec.push_back(std::make_unique<DerivedClass>()),你将永远不会有一个unique_ptr包含一个nullptr

@Berto99的回答中提到了问题(即UB) of calling the std::vector::back为空std::vector

此外,就像@RemyLebeau提到的,如果你使用std::make_unique,它总是return the std::unique_ptr of an instance of type T(i.e. BaseClass).

我想向您的 actual question. If you want to check anything regarding the last insertion, you could use std::vector::emplace_back 添加一些内容,其中 returns (C++17 起) 对插入元素的引用。

std::vector<std::unique_ptr<BaseClass>> vec;
auto& lastEntry = vec.emplace_back(std::make_unique<BaseClass>());

if (lastEntry) // pointer check
{
    // do something with the last entry!
}

std::vector::push_back 相比,您的 std::unique_ptr<BaseClass> 将就地建造。