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

Calling derived class method from base class destructor

本文关键字:派生 类方法 函数调用 析构 基类      更新时间:2023-10-16

>我在基类"SceneNode"中有以下析构函数代码片段,它试图清除其成员向量并删除从 SceneNode 派生的向量对象,但在删除子>到字符串行时出现错误,您能否指出正确的方向:

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()] [..srclibscenenodeSceneNode.cpp:30] Node children size: 1 [SceneNode]
2015-03-09 15:33:39,685 DEBUG [default] [] [virtual lib::SceneNode::~SceneNode()] [..srclibscenenodeSceneNode.cpp:34] Deleting 
2015-03-09 15:33:39,685 FATAL [default] CRASH HANDLED; Application has crashed due to [SIGSEGV] signal

谢谢!

首先更改以下内容:

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

对此:

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

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

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