我正在尝试学习如何有效地使用智能指针,并以更“ OOP”的意义进行编程。
基本上,我遇到的问题如下:
// base class example
class class_a {
public:
virtual void func( ) = 0;
std::shared_ptr< class_a > m_parent;
std::vector< std::shared_ptr< class_a > > m_children { };
void add_child( std::shared_ptr< class_a > a ) {
m_parent = this; // here! how could I go about this?
m_children.emplace_back( a );
}
};
// derived class example
class class_b : public class_a {
int m_var { };
public:
class_b( int param ) : m_var( param ) { }
void func( ) override {
// stuff
}
};
/*
* elsewhere
*/
auto parent = std::make_shared< class_b >( 14 );
{
// class_c inherits 'class_a' like 'class_b'
auto child = std::make_shared< class_c >( 6 );
{
// more children
}
parent->add_child( child );
}
致谢。
答案 0 :(得分:1)
您似乎正在尝试将新子“连接”到其父。
然后只需为子内部变量分配一个引用。
a->m_parent = this;
正如其他人指出的那样,请使用 weak_ptr 而不是共享指针来保留您孩子的父级引用,否则在删除父节点时,父级仍将保持对子级的作用而不是被垃圾收集。
答案 1 :(得分:-1)
很显然,您的存储层次结构中存在循环。在这种情况下,有一个称为weak_ptr
的原语。将您的父指针设置为DoCmd.RunCommand acCmdSaveRecord
。
可能是您的代码有误,我建议将weak_ptr
更改为此
class_a