C++继承在堆栈上不起作用?
这是一个更大代码的缩小问题。我知道 Ca 应该在堆上,但我想避免更改“。”到“->”代码中随处可见。有什么办法可以绕过这个错误吗? (编译器是g++ 4.6.1) 我认为这是一个错误,因为 c++ 允许它但行为不正确......
#include <iostream>
using namespace std;
class AA {
public:
virtual void foo() {
cout << "AA!\n";
};
};
class AB : public AA {
public:
AB() : AA() { cout << "construct AB!\n"; }
void foo() {
cout << "AB!\n";
}
};
class C {
public:
AA a;
void xchg() {
a.~AA();
new (&a) AB(); // everything works here except virtuals
}
};
int main() {
C c;
c.a.foo(); // -> AA
c.xchg();
c.a.foo(); // -> AA :(
AA *aa = new AB();
aa->foo(); // -> AB (virtual works)
return 0;
};
This is a down-sized problem of a much larger code. I know C.a should be on the heap but I want to avoid changing "." to "->" everywhere in the code. Is there a way I can circumvent this bug? (compiler is g++ 4.6.1)
I consider this a bug since c++ allows it but does not behave appropriately...
#include <iostream>
using namespace std;
class AA {
public:
virtual void foo() {
cout << "AA!\n";
};
};
class AB : public AA {
public:
AB() : AA() { cout << "construct AB!\n"; }
void foo() {
cout << "AB!\n";
}
};
class C {
public:
AA a;
void xchg() {
a.~AA();
new (&a) AB(); // everything works here except virtuals
}
};
int main() {
C c;
c.a.foo(); // -> AA
c.xchg();
c.a.foo(); // -> AA :(
AA *aa = new AB();
aa->foo(); // -> AB (virtual works)
return 0;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
唯一的错误是在你的代码中。您正在调用未定义的行为(实际上以几种不同的方式)。
标准不需要对此进行诊断,编译器没有责任确保您不做任何愚蠢的事情。
The only bug is in your code. You are invoking undefined behavior (in several different ways, actually).
The Standard does not require a diagnostic for this, it's not the compiler's responsibility to make sure you don't do anything stupid.
这实际上不起作用:这里的行为是未定义的。
a
是AA
类型的对象。您无法在其位置构造AB
类型的对象。唯一允许您构造的对象是AA
对象。如果您需要。另请注意,
a
的多态行为,则应该使用指向动态分配对象的指针。优选地,智能指针指向动态分配的对象,例如std::unique_ptrAA
应该有一个虚拟析构函数。This doesn't really work: the behavior here is undefined.
a
is an object of typeAA
. You cannot construct an object of typeAB
in its place. The only kind of object you are permitted to construct there is anAA
object.If you need polymorphic behavior for
a
, you should use a pointer to a dynamically allocated object. Preferably, a smart pointer to a dynamically allocated object, e.g., astd::unique_ptr<AA>
. Note also thatAA
should have a virtual destructor.