My compiler doesn't support make_unique. How to write one?
template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args );
My compiler doesn't support make_unique. How to write one?
template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args );
Version by Stephan T. Lavavej (also known by STL) who originally proposed adding this function to C++14
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
namespace std {
template<class T> struct _Unique_if {
typedef unique_ptr<T> _Single_object;
};
template<class T> struct _Unique_if<T[]> {
typedef unique_ptr<T[]> _Unknown_bound;
};
template<class T, size_t N> struct _Unique_if<T[N]> {
typedef void _Known_bound;
};
template<class T, class... Args>
typename _Unique_if<T>::_Single_object
make_unique(Args&&... args) {
return unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template<class T>
typename _Unique_if<T>::_Unknown_bound
make_unique(size_t n) {
typedef typename remove_extent<T>::type U;
return unique_ptr<T>(new U[n]());
}
template<class T, class... Args>
typename _Unique_if<T>::_Known_bound
make_unique(Args&&...) = delete;
}
EDIT: updated code to the N3656 standard revision
_Known_bound
version when make_unique
is used correctly. If someone tries to use it as make_unique<T[N]>()
it'll match the _Known_bound
version and result in an error.
Jul 27, 2013 at 22:56
make_unique
.
Mar 25, 2016 at 21:32
Copied from make_unique and perfect forwarding (the same is given in Herb Sutter's blog)
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
If you need it in VC2012, see Is there a way to write make_unique() in VS2012?
Nevertheless, if the solution in sasha.sochka's answer compiles with your compiler, I would go with that one. That is more elaborate and works with arrays as well.
std::forward
, and not to T
. (Maybe I misunderstand your question.)
...
syntax, only what I have seen in examples. What seems weird to me is that in the line std::forward<Args>(args)...
it seems that args
now somehow means each parameter individually while at the top it meant all of the parameters as a unit.
Mar 29, 2019 at 23:30
make_unique
to create an array type like unsigned char[]
and yields the error message Allocation of incomplete type
.
Sep 24, 2019 at 15:45