C++ make_shared not available

柔情痞子 提交于 2019-11-30 05:42:37

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/9135144/c-make-shared-not-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!