Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ make_shared not available

While I have std::tr1::shared_ptr<T> available in my compiler, I don't have make_shared.

Can someone point me to a proper implementation of make_shared? I see that I need to use varargs to provide arguments to constructor of T.

But I don't have variadic templates available in my compiler as well.

like image 316
user231536 Avatar asked Feb 03 '12 20:02

user231536


People also ask

What is Make_shared in C++?

Description. It constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr that owns and stores a pointer to it.

What is the difference between Make_shared and shared_ptr?

The difference is that std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two.

Should I use Make_shared?

Whenever possible, use the make_shared function to create a shared_ptr when the memory resource is created for the first time. make_shared is exception-safe. It uses the same call to allocate the memory for the control block and the resource, which reduces the construction overhead.

Why is Make_shared more efficient?

One reason is because make_shared allocates the reference count together with the object to be managed in the same block of memory.


1 Answers

If your compiler don't give an implementation of make_shared and you can't use boost, and you don't mind the lack of single-allocation optimization both for the object and the reference counter then make_shared is something like this:

Without variadic template support:

// zero arguments version
template <typename T>
inline shared_ptr<T> make_shared()
{
  return shared_ptr<T>(new T());
}

// one argument version
template <typename T, typename Arg1>
inline shared_ptr<T> make_shared(Arg1&& arg1)
{
  return shared_ptr<T>(new T(std::forward<Arg1>(arg1)));
}

// two arguments version
template <typename T, typename Arg1, typename Arg2>
inline shared_ptr<T> make_shared(Arg1&& arg1, Arg2&& arg2)
{
  return shared_ptr<T>(new T(std::forward<Arg1>(arg1),
                             std::forward<Arg2>(arg2)));
}

// ...

If your compiler don't support r-value references, then make 2 versions for each arguments count: one const Arg& and one Arg&

With variadic template support:

template <typename T, typename... Args>
inline shared_ptr<T> make_shared(Args&&... args)
{
  return shared_ptr<T>(new T( std::forward<Args>(args)... ));
}
like image 176
Gigi Avatar answered Sep 18 '22 22:09

Gigi