Starting with Boost 1.57, there is an official implementation of unique_ptr in the Boost.Move library.
From the documentation :
(...) plugin replacement for std :: unique_ptr, also used from C ++ 03 Compilers.
The code is available in the header file <boost/move/unique_ptr.hpp> and is located in the boost::movelib . In addition, the Boost.Move library provides the factory function make_unique() in <boost/move/make_unique.hpp> , also in the boost::movelib .
Therefore, the example from the question can be implemented as follows:
#include <boost/move/unique_ptr.hpp> using boost::movelib::unique_ptr; unique_ptr<Base> create_base() { return unique_ptr<Base>(new Derived); }
See a live example on Wandbox . Note that the code compiles fine with gcc 4.6.4 in C ++ 98 mode (!).
What is interesting in boost::movelib::unique_ptr as applied to your case with base / derived classes, the implementation provides compile-time checking to declare a virtual destructor in the base class. If you skip it , the code will not compile (click the "Run (...)" button to see the compiler error message).
One small problem is that this includes files from the boost/move directory, but the code is in the boost::movelib (a little difference, but it can be annoying).
See also the topic in the expanded newsletter for more information.
Thanks to Ion Gaztanyaga for this absolutely unique and useful piece of code.
Adam Romanek Jan 28 '15 at 13:05 2015-01-28 13:05
source share