相关疑难解决方法(0)

是否允许删除?

是否允许delete this;delete-statement是将在该类实例上执行的最后一个语句?当然,我确信this-pointer所代表的对象是newly-created.

我在考虑这样的事情:

void SomeModule::doStuff()
{
    // in the controller, "this" object of SomeModule is the "current module"
    // now, if I want to switch over to a new Module, eg:

    controller->setWorkingModule(new OtherModule());

    // since the new "OtherModule" object will take the lead, 
    // I want to get rid of this "SomeModule" object:

    delete this;
}
Run Code Online (Sandbox Code Playgroud)

我可以这样做吗?

c++ memory-management new-operator self-destruction delete-operator

225
推荐指数
8
解决办法
10万
查看次数

何时在null实例上调用成员函数会导致未定义的行为?

请考虑以下代码:

#include <iostream>

struct foo
{
    // (a):
    void bar() { std::cout << "gman was here" << std::endl; }

    // (b):
    void baz() { x = 5; }

    int x;
};

int main()
{
    foo* f = 0;

    f->bar(); // (a)
    f->baz(); // (b)
}
Run Code Online (Sandbox Code Playgroud)

我们期望(b)崩溃,因为x空指针没有相应的成员.在实践中,(a)不会崩溃,因为this从不使用指针.

因为(b)取消引用this指针((*this).x = 5;),并且this为null,程序进入未定义的行为,因为取消引用null总是被称为未定义的行为.

(a)导致未定义的行为吗?如果两个函数(和x)都是静态的呢?

c++ standards-compliance null-pointer undefined-behavior language-lawyer

115
推荐指数
2
解决办法
1万
查看次数