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

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

本文关键字:段错误 错误 this-pointer 构造函数 继承 堆栈 C++      更新时间:2023-10-16

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

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

您需要覆盖赋值运算符:

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