Francis Cugler
Francis Cugler

Reputation: 7925

Self containing shared_ptr of itself that is inherited from std::enable_shared_from_this

This question is a follow up question of this question here: original question

I have a class that inherits from std::enable_shared_from_this and this class contains a std::shared_ptr<Self>

In any of this class's constructors after I know that the class's details are complete and successful how do I go about assigning the stored std::shared_ptr<Self> to be that of the shared this?

Example:

class Self : public std::enable_shared_from_this<Self> {
private:
    std::shared_ptr<Self> me_; // Or
    std::unique_ptr>Self> me_;

public:
    Self ( /*some parameters*/ );
};

Self::Self( /* some parameters */ ) {
    // Check parameters for creation

    // Some work or initialization being done

    // If all is successful and construction of this class is about
    // to leave scope, then set the smart pointer to the this*

    // How to do ...
    me_ = std::enable_shared_from_this<Self>::shared_from_this();
    // Properly if this is even possible at all.
}

Upvotes: 0

Views: 3076

Answers (2)

hlscalon
hlscalon

Reputation: 7552

You can't because you must be an existing std::shared_ptr that points to the current object. As Scott Meyers says in Effective Modern C++ (chapter 19), you could declare your constructors private, and make a factory function returning a std::shared_ptr, like :

class Self: public std::enable_shared_from_this<Self> {
public:
// factory function that perfect-forwards args
// to a private ctor
    template<typename... Ts>
    static std::shared_ptr<Self> create(Ts&&... params);
    ...
    void process();
    ...
private:
    ... // ctors
};

And then call process, that could be something like:

void Self::process() 
{
    ... 
    me_ = shared_from_this();
}

Upvotes: 1

Jason R
Jason R

Reputation: 11768

You can't. At that point, the shared_ptr that points to the current Self instance doesn't exist yet. It can't possibly exist until after the constructor returns. shared_from_this() has a precondition that a shared_ptr already exists that points to this.

Upvotes: 2

Related Questions