有人能简单解释一下这不起作用的原因吗:
std::shared_pointer<Bar> getSharedPointer() {
return std::make_shared<Bar>();
}
...
auto foo = getSharedPointer().get();
显然使用原始指针 foo
会导致段错误,因为 getSharedPointer()
返回的共享指针的生命周期将用完。不知怎的,我希望它能持续到它的范围结束(就像它在里面的任何 block 一样)。
这是正确的吗?有没有类似的例子?
最佳答案
对于 getSharedPointer().get();
,getSharedPointer()
返回一个临时的 std::shared_ptr
,它将在表达式立即删除,它管理的指针也将被删除。之后 foo
将变为悬挂状态,对它的任何取消引用都会导致 UB。
auto foo = getSharedPointer().get();
// foo have become dangled from here
您可以改用命名变量:
auto spb = getSharedPointer();
auto foo = spb.get();
// It's fine to use foo now, but still need to note its lifetime
// because spb will be destroyed when get out of its scope
// and the pointer being managed will be deleted too
关于c++ - 共享指针和原始指针生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41885725/