繁体   English   中英

如何检查 std::unique_ptr 是否为 null,如果它在 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!
}

但无论指针的内容如何,它总是返回 false。

正如你可以从这里读到的,如果向量是空的,它就是 UB。 如果不是你的情况,你可以从这里读到, unique_ptr有一个operator bool()来检查object 当前是否由unique_ptr管理

所以,与:

vector.empty();

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

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

您检查第一个unique_ptr是否指向 object。

PS:如果你总是使用vec.push_back(std::make_unique<DerivedClass>()) ,你永远不会有一个持有nullptrunique_ptr

@Berto99的答案提到了为空std::vector调用std::vector::back的问题(即UB )。

此外,就像@RemyLebeau提到的那样,如果您使用std::make_unique ,它将始终返回类型T (即BaseClass )实例的std::unique_ptr

我想在您的实际问题中添加一些内容。 如果要检查有关最后插入的任何内容,可以使用std::vector::emplace_back ,它返回(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>将就地构建。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM