简体   繁体   中英

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 ?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM