[英]Why does it NOT seg fault on dereference? unique_ptr
我希望以下代码在进入方法内部并打印任何内容之前会出现分段错误。 为什么不呢? 例如,执行如何进入方法并打印输出?
#include <memory>
#include <vector>
#include <iostream>
class Foo{
public:
void method(int x){
std::cout << "wut" << std::endl;
m_list.push_back(x);
}
private:
std::vector<int> m_list;
};
int main()
{
std::unique_ptr<Foo> example;
example->method(0);
}
当然,正如其他人指出的那样,这是未定义的行为。
然而,在许多 C++ 实现中,这确实不会在输出之后崩溃,因为在此之前NULL
指针实际上从未被取消引用。
您的main
基本上归结为reinterpret_cast<Foo *>(nullptr)->method(0)
。 由于method
是class Foo
的非virtual
方法,因此转换为Foo::method(0)
( this
设置为nullptr
)。
输出线不参照this
根本,所以只有当m_list
被访问的this
是第一次解引用(并因此崩溃)。
如果method
是virtual
,对它的调用很可能会崩溃,因为在典型的实现中,对virtual
方法的调用会取消引用this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.