C++ 中的构造函数、继承、堆栈、堆、this 指针和段错误

constructors,inheritance,stack,heap,this-pointer and segfaults in c++

我为一些不知道如何命名和如何解决的代码而苦恼。我试图将代码缩减为以下示例(因此示例本身没有意义,但它显示了问题所在):

 struct MyInterface {
    virtual ~MyInterface() {

    };
    virtual void Output() = 0;
};

class A {
public:
    MyInterface *myInterface;
    A(MyInterface *myInterface) {
        std::cout << "this in A constructor: " << this << std::endl;
        this->myInterface = myInterface;
    }
    void CallA() {
        this->myInterface->Output();
    }
};

class B : public MyInterface, A {
public:
    int v;
    B(int v) : A(this) {
        std::cout << "this in B constructor: " << this << std::endl;
        this->v = v;
    }
    virtual void Output() override {
        std::cout << "Whatever" << std::endl;
    }
    void CallB() {
        std::cout << "this in CallB: " << this << std::endl;
        this->CallA();
    }
};

class Foo {
public:
    B b;
    Foo() : b(42) {
        b = B(41);  //This will make an "invalid" B:
                    //generates B on the Stack but assign the bytes to Foo.b (which is on the the heap)
                    //so b.myInterface will point to the stack
                    //after leaving this context b.other will be invalid
    }
    void Exec() {
        b.CallB();
    }
};
int main(int argc, char **args) {
    Foo *foo = new Foo();
    foo->Exec();    //Gives a segfault, because foo->b.myInterface is not valid
    return 0;
}

首先我认为它与继承及其虚方法有关。但我认为主要问题是构造函数中的 this 指针。

所以我的问题是:构造b时,构造函数中的this指针指向栈。为什么不显示指向目标内存(在堆中)的 this 指针?没有调用复制构造函数 - 为什么? 我该如何命名这个问题?

没有调用复制构造函数,因为您没有创建要分配给现有对象的新对象。这调用赋值运算符。

这是复制构造:

B b1(42); // construction
B b2(b1); // copy construction
B b3 = b1; // looks like assignment but is actually copy construction

这是作业:

B b1(42); // construction
b1 = B(43); // b1 already exists we can't copy construct, construct a new object and assign to b1

您需要覆盖 assignment operator:

class B
{
   B& operator=(const B& other)
   {
      // fix references to this here
   }
}