Search code examples
c++shared-ptr

shared_ptr - why does it break?


While developing a tree-like data structure, I wrote something like this:

    #include <memory>

    class Node: public std::enable_shared_from_this<Node> {
    public:

        void set_root(Node & n);
    private:
        std::shared_ptr<Node> root;
        std::shared_ptr<Node> leaf;
    };

    void Node::set_root(Node & n) {
        root = n.shared_from_this();
        n.leaf = shared_from_this();
    }

    int main() {
        Node n1, n2;
        n1.set_root(n2);
    }

The code compiles with clang but breaks run-time ("libc++abi.dylib: terminating with uncaught exception of type std::__1::bad_weak_ptr: bad_weak_ptr") Why?

EDIT So based on the answers, I came up with the version that seems to be working:

    #include <memory>

    class Node;
    typedef std::shared_ptr<Node> Node_SP;

    class Node: public std::enable_shared_from_this<Node> {
    public:

        void set_root(Node & n);
    private:
        std::shared_ptr<Node> root;
        std::shared_ptr<Node> leaf;
    };

    void Node::set_root(Node & n) {
        root = n.shared_from_this();
        n.leaf = shared_from_this();
    }

    int main() {
        Node_SP n1 = std::shared_ptr<Node>(new Node);
        Node_SP n2 = std::shared_ptr<Node>(new Node);

        n1->set_root(*n2);
    }

Solution

  • shared_ptr assumes the object is allocated on the heap, but you've allocated it on the stack.

    Use new instead and let shared_ptr call delete for you.