奇怪的访问冲突错误

Jal*_*eri 2 c++ access-violation

我写了一个使用继承的程序,一切都还可以,但我认为这个错误不应该在这里自然而然.这是我的计划:

class A
{
protected:
    int x;
public:
    A(){};
    ~A(){};
    A* operator=(const A* other)
    {
        this->x = other->x;
        return this;
    }
};
class B : public A
{
public:
    B() : A(){};
    ~B(){};
};
class C
{
protected:
    A *a;
public:
    C(const A* other){ *(this->a) = other; };
};

int main()
{
    B *b = new B();
    C *c = new C(b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它在语句'this-> x = other-> x;'中产生执行时错误.那这个呢?

Luc*_*ore 7

*(this->a)是未定义的行为,因为this->a没有初始化 - 它只是一个悬垂的指针.

您可以使用a = new A; *a = other(this->在这种情况下是冗余的),但这不是正确的C++方式 - 您应该使用RAII(查找它) - 如果您这样做,则不需要析构函数,赋值运算符或复制构造函数.

此外,operator =通常*this通过引用返回.