Search code examples
c++qtshared-ptr

My program crashed when using shared_ptr, what's wrong with this code?


I'm learning smart pointers but i don't understand it very well, What I have already known is that it will auto delete the object it points to, but i have no idea why my program crashes. Please see the following code:

#include <QVector>
#include <memory>
using std::shared_ptr;
using std::make_shared;

class Node;
typedef shared_ptr<Node> NodePtr;

class Node {
  public:
    Node(){};

    NodePtr AddInput(NodePtr n){
        // i wanted to convert the "Node* this" to shared_ptr<Node>, 
        // thus it can be added to n->outputs_.
        NodePtr this_ptr(this);  


        if (!inputs_.contains(n)) {
            inputs_.append(n);
        }
        if (!n->outputs_.contains(this_ptr)) {
            n->outputs_.append(this_ptr);
        }
        return this_ptr;
    }

  public:
    QVector<NodePtr> inputs_;
    QVector<NodePtr> outputs_;
};


int main(){
    auto g1 = make_shared<Node>();
    auto g2 = make_shared<Node>();
    g2->AddInput(g1);
    g1->outputs_.clear();  // the program crashes when executing this line
    return 0; // never goes here
}

the program crashes when executing "g1->outputs_.clear()" but it's OK when I replace it with "g2->inputs_.clear()" ? Why ? What happened ? How should I fix it ?


Solution

  • thanks, shared_from_this() solves my problem

    class Node : public std::enable_shared_from_this<Node>
    {
      public:
        Node(){};
        NodePtr AddInput(NodePtr n){
            NodePtr this_ptr = shared_from_this();
    
            if (!inputs_.contains(n)) {
                inputs_.append(n);
            }
            if (!n->outputs_.contains(this_ptr)) {
                n->outputs_.append(this_ptr);
            }
            return this_ptr;
        }
    
      public:
        QVector<NodePtr> inputs_;
        QVector<NodePtr> outputs_;
    };