c++ - 共享指针和原始指针生命周期

标签 c++ pointers smart-pointers lifetime temporary

有人能简单解释一下这不起作用的原因吗:

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/

相关文章:

c++ - 输出 cout 是感叹号。 C++

c++ - 我应该为 map 中的两个智能指针对制作自己的比较器吗?

c++ - C - 一次从 stdin BUFSIZE 字符读取

c++ - 字节流实现 - 偏移量是否正确实现?

c - 为什么我不能递增数组?

c - 如果 C 有指针,为什么它需要数组?

c++ - std::vector<char> 并获取下一行到定界字符

c++ - 如何创建对 const 指针的 const 引用?

C 从函数返回 const char 指针或 char 指针

C++ 引用计数 : use a Macro to do it, 有什么优点?