¿Cómo implementar la función make unique en C++11? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Mi compilador no soporta make_unique. Cómo escribir uno?

template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args );
Author: sasha.sochka, 2013-07-28

2 answers

Copiado de make_unique and perfect forwarding (lo mismo se da en 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)...));
}

Si lo necesita en VC2012, vea ¿Hay alguna manera de escribir make_unique() en VS2012?


Sin embargo, si la solución en sasha.la respuesta de sochka compila con tu compilador, yo iría con ese. Eso es más elaborado y funciona con matrices también.

 24
Author: Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:01

Versión de Stephan T. Lavavej (también conocido por STL) que originalmente propuso agregar esta función a 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;
}

EDITAR: código actualizado a la revisión estándar N3656

 42
Author: sasha.sochka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-27 21:14:24