Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c++11 - Is unique_ptr<Derived> to unique_ptr<Base> up-casting automatic?

I know it is possible that a derived class unique_ptr can take place where base class unique_ptr is required for polymorphic types. For example, while returning from function

unique_ptr<Base> someFunction()
{
     return make_unique<Derived>(new Derived());
}

or passing to function as argument.

// Function taking unique pointer
void someOtherFunction(unique_ptr<Base>&& ptr)
// Code calling this function
someOtherFunction(std::move(ptrToDerived));

My question is: Is this upcasting always automatic? Or do we need to explicitly perform it using dynamic_cast?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The (draft) standard says:

// 20.8.1.2.1, constructors
...
template <class U, class E>
  unique_ptr(unique_ptr<U, E>&& u) noexcept;
template <class U>
  unique_ptr(auto_ptr<U>&& u) noexcept;

Those are constructors from any unique_ptr. The standard further restricts their usage by clauses like this:

24 Remarks: This constructor shall not participate in overload resolution unless U* is implicitly convertible to T* and D is the same type as default_delete<T>

The effect of this remark is that unique_ptr<T> is constructible from unique_ptr<U> precisely U* is convertible to T* (and all deleter requirements are met). In particular, when T is an unambiguous public base class of U.

Since the constructor is not explicit, it serves as an implicit converter from unique_ptr<U> to unique_ptr<T>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...