从基类析构函数调用派生类方法

时间:2015-03-09 04:45:09

标签: c++

我在基类“SceneNode”中有以下片段的析构函数代码,它试图清除其成员向量并删除从SceneNode派生的向量对象,但在删除子 - > toString <时出现错误/ strong> line,能不能指出正确的方向:

SceneNode::~SceneNode() {

LOG(DEBUG)<< "Node children size: " + to_string(children.size()) + " [" + toString() + "]";

// clean children nodes
for (SceneNode* child : children) {
    LOG(DEBUG) << "Deleting ";
    LOG(DEBUG) << "Deleting " + child->toString();
    delete child;
    LOG(DEBUG) << "Deleted " + child->toString();
}

当我调试时,它会在那里显示一个正确的派生对象:

    Name : child
Details:0x3204b40
Default:0x3204b40
Decimal:52448064
Hex:0x3204b40
Binary:11001000000100101101000000
Octal:0310045500

Name : lib::SceneNode
Details:{_vptr.SceneNode = 0x4e3430 <vtable for lib::ImageSceneNode+16>, id = {static npos = <optimized out>, _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x3204c08 "New Node"}}, position = {x = 0, y = 0}, size = {x = 1920, y = 1080}, center = {x = 960, y = 540}, rotation = 0, alpha = 255, enabled = true, visible = true, deleted = false, parent = 0x22fca0, children = {<std::_Vector_base<lib::SceneNode*, std::allocator<lib::SceneNode*> >> = {_M_impl = {<std::allocator<lib::SceneNode*>> = {<__gnu_cxx::new_allocator<lib::SceneNode*>> = {<No data fields>}, <No data fields>}, _M_start = 0x0, _M_finish = 0x0, _M_end_of_storage = 0x0}}, <No data fields>}, animators = {<std::_Vector_base<lib::NodeAnimator*, std::allocator<lib::NodeAnimator*> >> = {_M_impl = {<std::allocator<lib::NodeAnimator*>> = {<__gnu_cxx::new_allocator<lib::NodeAnimator*>> = {<No data fields>}, <No data fields>}, _M_start = 0x0, _M_finish = 0x0, _M_end_of_storage = 0x0}}, <No data fields>}, sceneManager = 0x22fc98}
Default:{...}
Decimal:{...}
Hex:{...}
Binary:{...}
Octal:{...}

日志:

2015-03-09 15:33:39,685 DEBUG [default] [] [virtual lib::SceneNode::~SceneNode()] [..\src\lib\scene\node\SceneNode.cpp:30] Node children size: 1 [SceneNode]

2015-03-09 15:33:39,685 DEBUG [default] [] [virtual lib::SceneNode::~SceneNode()] [..\src\lib\scene\node\SceneNode.cpp:34] Deleting 

2015-03-09 15:33:39,685 FATAL [default] CRASH HANDLED; Application has crashed due to [SIGSEGV] signal

谢谢!

1 个答案:

答案 0 :(得分:2)

首先改变这个:

LOG(DEBUG) << "Deleting " + child->toString();

到此:

LOG(DEBUG) << "Deleting " << child->toString();

然后删除此行,因为此时变量已被销毁而您无法访问它(这是崩溃的原因):

LOG(DEBUG) << "Deleted " + child->toString();