【问题标题】:undefined behaviour to use raw pointer from a deleted shared_ptr?使用来自已删除 shared_ptr 的原始指针的未定义行为?
【发布时间】:2017-02-02 07:06:39
【问题描述】:

我有以下代码

#include <iostream>
#include <memory>
#include <cassert>

int main()
{
    void* p_any = nullptr;

    {
        auto  p_src = std::make_shared<int>(10); // new instance        
        p_any = p_src.get();                     // get raw unmanaged pointer?
        auto  p_again = reinterpret_cast<int*>(p_any);
        assert(*p_src == *p_again);
    }

    auto  p_again = reinterpret_cast<int*>(p_any); // ??
    std::cout << *p_again <<  "\n";                // undefined?, expected?

}

最后两个语句安全吗?

我可以运行它http://cpp.sh/6poh 而不输出“10”, 但这是预期的吗?还是只是未定义的行为?

【问题讨论】:

  • assert(*p_src = *p_again); - 你确定这里不应该是==吗?
  • 修正错字,谢谢
  • 你不能取消引用指向不存在对象的指针,所以不,不安全。
  • 是的,它是 UB。指针已被删除;取消引用是 UB。
  • cout &lt;&lt; '\n'cout &lt;&lt; "\n" 好一点

标签: c++ pointers shared-ptr undefined-behavior invalid-pointer


【解决方案1】:

p_src 对象超出了右括号的范围,并且由于没有其他共享指针实例,包含的指针将被删除。所以p_any 将指向已删除的数据,您确实会有未定义的行为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2021-07-15
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多