我有以下代码:
struct Message
{
explicit Message(const std::string& message) : selfMessage(message) {};
~Message() { std::cerr << "Message: " << selfMessage << std::endl; }
const std::string selfMessage;
};
struct Foo
{
Foo() : fooMessage("Foo") {}
/// Destructor here is left intentionally non-virtual !!!
~Foo() { std::cerr << "~Foo" << std::endl; }
Message fooMessage;
};
struct Bar : Foo
{
Bar() : barMessage("Bar") {}
~Bar() { std::cerr << "~Bar" << std::endl; }
Message barMessage;
};
int main()
{
std::auto_ptr<Foo> foo(new Bar);
}
我希望得到以下输出:
Message: Bar
Message: Foo
~Foo()
但实际上(代码是用 gcc
编译的)不打印 Message: Bar
据我了解barMessage
没有被正确销毁。为什么?
AFAIK 非虚拟 d-tor 仅影响派生类的 dtor 的调用 - 它永远不会被调用,但是派生类的堆栈分配成员呢?
谢谢,
附言我已经知道已弃用 std::auto_ptr<>()
用法:)
最佳答案
如果您通过指向基类对象的指针在派生对象上调用delete
,那么您将得到未定义的行为 除非基类被声明为虚拟的。
当基类上的模板化 std::auto_ptr
拥有派生类对象时,它会超出作用域,当实际对象为派生类类型。
关于c++ - 为什么在 g++ 中缺少虚拟 d-tor 不会破坏派生类的堆栈分配成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9682886/