P45 Imminent
P45 Imminent

Reputation: 8591

std::unique_ptr structure member to the structure type

Is

struct A
{
    std::unique_ptr<A> a;
};

allowed by the standard? I don't think it is for container types like std::set but is there something special about unique_ptr?

Upvotes: 5

Views: 393

Answers (3)

Galik
Galik

Reputation: 48615

According to this reference:

std::unique_ptr may be constructed for an incomplete type T, such as to facilitate the use as a handle in the Pimpl idiom. If the default deleter is used, T must be complete at the point in code where the deleter is invoked, which happens in the destructor, move assignment operator, and reset member function of std::unique_ptr.

So yes std::unique_ptr can be used in this way.

Upvotes: 0

Yes, it's explicitly allowed. C++14 (n4140) 20.8.1/5:

... The template parameter T of unique_ptr may be an incomplete type.

It is also allowed for std::shared_ptr and std::weak_ptr, using similar wording.

Upvotes: 4

Brian
Brian

Reputation: 892

Sure it's allowed. This basically an implementation of some kind of path.

Upvotes: 0

Related Questions