简体   繁体   English

std :: make_shared <Type> 造成内存泄漏

[英]std::make_shared<Type> creates memory leak

Valgrind gives me some memory leaks when I use std::make_shared: 当我使用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;
}

Why is make_shared giving me a memory leak? 为什么make_shared给我内存泄漏?

Edit: I have included the summary of the classes for better understanding of the code. 编辑:为了更好地理解代码,我提供了类的摘要。

you have 2 shared pointers owning each other. 您有2个彼此拥有的共享指针。

think of a clear ownership concept. 想出一个明确的所有权概念。 then store a std::weak_ptr in the non-owner. 然后将std::weak_ptr存储在非所有者中。 To access the non-owned object .lock() the weak_ptr and check the resulting shared_ptr before use. 要访问非拥有对象.lock() ,weak_ptr并在使用前检查生成的shared_ptr。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM