所以我问过以下这个问题:C++ return by value - what happens with the pointer inside?
我想知道是否我进一步强加父母必须有一个指向孩子的指针列表,是否有任何好的解决方案,因为在任何情况下都不会因为共享和弱指针而导致任何内存泄漏,因为我需要动态地在操作员体内分配内存。您可以假定计算图是非循环的。

具体考虑一下my.h:

class Interface{
public:
    int myid();
    Interface(double in);
    ~Interface(){
            std::cout<<"Destroy "<<myid()<<std::endl;
     }
    friend Interface operator+(const Interface& a, const Interface& b);
    void tree();
private:
    class Impl;
    std::shared_ptr<Impl> pimpl;
};
Interface operator+(const Interface& a, const Interface& b);


和my.cpp:

class autodiff::Interface::Impl{
public:
    static int id;
    int myid;
    double value;
    std::vector<std::shared_ptr<autodiff::Interface::Impl>> children;
    std::vector<std::weak_ptr<autodiff::Interface::Impl>> parents;
    Impl(double val) : value(val), myid(++id){};
    ~Impl(){
        std::cout<<"Destroy: "<<myid<<std::endl;
        for(auto it:children)
            it.reset();
    }
    void tree();

};

autodiff::Interface::Interface(double in){
    pimpl = std::make_shared<Impl>(in);
}

int autodiff::Interface::myid() {
    return pimpl->myid;
}

autodiff::Interface& autodiff::operator+(const Interface &a, const Interface &b) {
    Interface* ch = new Interface(a.pimpl->value + b.pimpl->value);
    a.pimpl->children.push_back(ch->pimpl);
    b.pimpl->children.push_back(ch->pimpl);
    ch->pimpl->parents.push_back(a.pimpl);
    ch->pimpl->parents.push_back(b.pimpl);
    return *ch;
}
void autodiff::Interface::tree() {
    pimpl->tree();
}
void autodiff::Interface::Impl::tree() {
    std::cout<<myid<<"-(";
    for(int i=0;i<parents.size();i++)
        if(auto tmp = parents[i].lock())
            std::cout<<tmp->myid<<",";
    std::cout<<")"<<std::endl;
    for(int i=0;i<parents.size();i++)
        if(auto tmp = parents[i].lock())
            tmp->tree();
}

int autodiff::Interface::Impl::id = 0;


输出为:

5-(4,3,)
4-(1,2,)
1-()
2-()
3-()
Destroy: 3
Destroy: 2
Destroy: 1


我想要和期望的地方是:

5-(4,3,)
4-(1,2,)
1-()
2-()
3-()
Destroy 3
Destroy 2
Destroy 1
Destroy 5
Destroy 4


我的问题是为什么临时创建的对象4和5不自动释放?在1,2,3被销毁之后,这些实例只能是weak_ptr,而没有shared_ptr还是我错了?

最佳答案

我没有阅读您以前的问题,但是当我一次编写二进制树实现时,我发现对子节点使用std::unique_ptr以及对父节点的简单观察原始指针很方便,例如

struct Node
{
    Node *parent;
    std::unique_ptr<Node> right;
    std::unique_ptr<Node> left;
};


所有这些都应初始化为std::nullptr。这样,一旦left被破坏,在rightNode下的整个子树都将被正确地破坏,因此无需递归地执行此操作。指向父节点的“观察指针”意味着您永远不要对其执行与内存相关的操作,尤其是不要删除。

09-20 16:57