gpt4 book ai didi

c++ - shared_ptr 的引用仍然是指针吗?

转载 作者:太空狗 更新时间:2023-10-29 19:40:17 24 4
gpt4 key购买 nike

最近在工作中对shared_ptr的引用有疑问。这是代码。

for (const auto & aRef : aVec) {
THROW_RUNTIME_IFNULLPTR(aRef);
// do sth
}

这是我同事的代码。在我看来,aRef 是一个永远不能为 null 的引用。虽然我被告知(通过 auto &)aRef 仍然是一个指针,所以它可能为空。引用只是为了不增加计数器。我对此很困惑。

不过,应该是这样的

for (const auto & aRef : aVec) {
// THROW_RUNTIME_IFNULLPTR(aRef);
if ( aRef ) {
aRef->getX();
}
// do sth
}

我错了吗?我不认为 aRef 是一个指针。

最佳答案

In my mind, aRef is a reference which can never be null.

是也不是。引用可以是它引用的对象可以是的一切。如果该对象是一个 intstd::stringstd::vector<double> ,那么它当然不能为 null(或者准确地说是 nullptr)。

但是,如果该对象是指针,例如 int* , 或 void* , 或 MyClass* , 那么它可以是 nullptr因为指针可以是 nullptr .

现在在你的例子中,被引用的对象是一个 std::shared_ptr .它在技术上不能是 nullptr , 但它可以代表 nullptr通过处于 get() 的状态返回 nullptr .

While I was told that (by auto &) aRef is still a pointer so it's possible that it's null.

更准确地说:aRef仍然是std::shared_ptr , 所以它可能仍然代表 nullptr .

关于c++ - shared_ptr 的引用仍然是指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42957355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com