-1 c++ smart-pointers std c++11
当我使用std :: make_shared时,Valgrind给了我一些内存泄漏:
TEST_F(CTestChild, add_gran_child) {
auto child{ std::make_shared<CChild>(TType::Home, std::make_shared<CMockParent>()) };
NiceMock<CMockCaller> caller;
auto gran_child( std::make_shared<CMockGranChild>(TType::Girl, child, caller) );
child->Add(gran_child);
EXPECT_EQ(child->GetCount(), 1);
}
class CMockParent : CParent{
public:
void something(void) override {}
}
class CParent{
public:
virtual void something(void) = 0;
}
class CChild{
public:
CChild(TType, shared_ptr<CParent> a) : _parent(a) {}
void Add(shared_ptr<CGranChild> a) { _list.push_back(a) }
shared_ptr<CParent> _parent;
TList<shared_ptr<CGranChild>> _list;
}
class CGranChild{
public:
CGranChild(TType, shared_ptr<CChild> a) : i_parent(a) {}
shared_ptr<CChild> _parent;
}
Run Code Online (Sandbox Code Playgroud)
为什么make_shared会给我一个内存泄漏?
编辑:我已经包含了类的摘要,以便更好地理解代码.
你有2个共享指针拥有彼此.
想到明确的所有权概念.然后std::weak_ptr在非所有者中存储一个.要访问非拥有对象.lock()weak_ptr并在使用之前检查生成的shared_ptr.
| 归档时间: |
|
| 查看次数: |
315 次 |
| 最近记录: |