11

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?

Tomilov Anatoliy
  • 15,657
  • 10
  • 64
  • 169

2 Answers2

5

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).

Oberon
  • 3,219
  • 15
  • 30
  • Really close alternative for me is [overloading](http://coliru.stacked-crooked.com/a/f87c5e9131d5eda7) of `make_shared` for `std::shared_ptr` itself somewhere in user namespace. – Tomilov Anatoliy Jan 28 '16 at 23:55
3

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270