我在一些我不知道如何命名和如何解决它的代码上苦苦挣扎。我试图将代码简化为以下示例(因此该示例本身没有意义,但它显示了问题):
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
指针?没有复制构造函数被调用-为什么?
我该如何命名这个问题?
答案 0 :(得分:3)
未调用复制构造函数,因为您没有创建要分配给现有对象的新对象。这将调用赋值运算符。
这是复制结构:
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
}
}