c++ - 为什么当我将指针分配给 NULL 时我的程序不会崩溃?

标签 c++

<分区>

我写了一个非常简单的代码。动态创建一个对象,然后删除该对象并将其分配给零。之后,我访问了该对象的成员函数,但我的程序并没有崩溃,而是返回了值。

class MyClass
{
public:
    MyClass() {}
    int funct() { return 0; }
};

int main()
{
    MyClass *mc = new MyClass;

    delete mc;
    mc = 0;

    // The program should crash here as I've set mc to zero after deleting 
    // it. But it returns the value.
    int retVal = mc->funct();

    return 0;
}

根据我对newdelete 和赋值给零的理解,这段代码应该崩溃,或者给出异常。

最佳答案

您可以将您的方法可视化为一个函数:

int funct(MyClass *this) { return 0; }

您可以看到该函数根本不使用 this,因此如果它为 0 也不会崩溃。

但是,不要在实际代码中做这样的事情。这仍然是一个未定义的行为,编译器优化可能会把它搞砸。

关于c++ - 为什么当我将指针分配给 NULL 时我的程序不会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45210574/

相关文章:

c++ - gcc编译错误: member of nested class A in template class Table is not visible in nested friend class. 为什么?

c++ - `decltype` 作为模板函数声明中模板类型规范的一部分

c++ - 让一个窗口相信它仍然在焦点上,尽管它不是

c++ - 模板以及编译期间创建的内容

c++ - 是否允许编译器像带有 -O2 的英特尔 C++ 编译器那样删除无限循环?

c++ - 编码(marshal)处理 - 将 std::vector<char> 转换为 string^ 反之亦然

c++ - 错误 Xcode 5.1 : unknown argument: '-cclib' [-Wunused-command-line-argument-hard-error-in-future]

c++ - GetPixel 返回不正确的值

c++ - 高效计算字典序中特定元素的索引

c++ - 有没有办法通过windbg查看堆栈帧上指针存储的地址?