最近在工作中对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.
是也不是。引用可以是它引用的对象可以是的一切。如果该对象是一个 int
或 std::string
或 std::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/