Using C++11, let's say I have factory functions dealing with base and derived classes:
#include <memory>
using namespace std;
struct B { virtual ~B() {} };
struct D : B {};
unique_ptr<B> MakeB()
{
auto b = unique_ptr<B>( new B() );
return b; // Ok!
}
unique_ptr<B> MakeD()
{
auto d = unique_ptr<D>( new D() );
return d; // Doh!
}
On the last line above, I need move(d)
in order to make it work, otherwise I get "Error: invalid conversion from std::unique_ptr<D>
to std::unique_ptr<D>&&
." My intuition said that in this context, the compiler should know that it could implicitly make d
an rvalue and move it into the base pointer, but it doesn't.
Is this a non-conformancy in my compilers (gcc 4.8.1 and VS2012)? The intended design of unique_ptr
? A defect in the standard?
Update: C++14 fixes this. Newer compilers such as GCC 9 accept the original code even with -std=c++11
.