0

我有以下代码

#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?

}

最后两个语句安全吗?

我可以在没有输出“10”的情况下运行它http://cpp.sh/6poh,但这是预期的吗?还是只是一个未定义的行为?

4

1 回答 1

4

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

于 2017-02-02T07:11:43.120 回答