infinitezero
infinitezero

Reputation: 2077

How do I explicitely initialize the copy constructor for a class that inherits from std::enable_shared_from_this

Consider the following test code:

#include <memory>

class C : public std::enable_shared_from_this<C>
{
    public:
    C(C const& c){}
};

int main()
{

}

Compiling this with -Wextra will generate the following warning

warning: base class 'class std::enable_shared_from_this' should be explicitly initialized in the copy constructor [-Wextra]

How do I do this correctly? Is there anything that I could trip over in more complicated classes?

Upvotes: 1

Views: 389

Answers (1)

Brian Bi
Brian Bi

Reputation: 119641

You can explicitly initialize it by calling its default constructor like this:

C(C const& c) : enable_shared_from_this() {}

You can also do it by calling its copy constructor like this:

C(C const& c) : enable_shared_from_this(c) {}

The copy constructor actually does the same thing as the default constructor (it marks the current object as not being owned by a shared_ptr) This ensures that the following will do the sensible thing:

C(C const& c) = default;  // also calls the copy constructor of the enable_shared_from_this base

When an object is copied, you get a new object, so, obviously, it's not owned by the same shared_ptr that the other object is.

Upvotes: 3

Related Questions