Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static member function make_shared of shared_ptr

Using libc++ I find out std::shared_ptr::make_shared() static member function in public section. It is very handy when I have already defined type alias to std::shared_ptr's specialization:

using T = int;
using P = std::shared_ptr< T >;
auto p = P::make_shared(123); // <=> std::make_shared< T >(123)
static_assert(std::is_same< decltype(p), P >::value);

I'm worry about standard compliance, because articles (1, 2) from trusted source mentions nothing about static member function make_shared of std::shared_ptr.

Is it bad parctice to use the function currently? Why?

like image 863
Tomilov Anatoliy Avatar asked Jan 28 '16 23:01

Tomilov Anatoliy


2 Answers

When using this static make_shared member function you depend on an implementation-specific extension of g++ / its standard library, as you already know. For the little gain you get from it, I would rather keep my code portable and use std::make_shared.

For the case you mentioned, i.e. constructing a new object using copy or move constructor from an existing one, I can suggest an alternative (untested; for C++11-compatibility you would have to add a trailing return type):

template <typename T>
auto share_ptr_to_new(T&& v) {
    using T2 = typename std::remove_reference<T>::type;
    return std::make_shared<T2>(std::forward<T>(v));
}

In the example above, you could then just write auto p = share_ptr_to_new(123).

like image 100
Oberon Avatar answered Oct 19 '22 19:10

Oberon


FWIW, there is

template<class T, class... Args> shared_ptr<T> make_shared(Args&&... args);

as a non-member function.

You should be able to use std::make_shared instead of std::shared_ptr::make_shared.

like image 28
R Sahu Avatar answered Oct 19 '22 17:10

R Sahu