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?
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)
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With