【发布时间】: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 << '\n'比cout << "\n"好一点
标签: c++ pointers shared-ptr undefined-behavior invalid-pointer