[英]C++ make_shared not available
While I have std::tr1::shared_ptr<T>
available in my compiler, I don't have make_shared
. 虽然我的编译器中提供了
std::tr1::shared_ptr<T>
,但是我没有make_shared
。
Can someone point me to a proper implementation of make_shared
? 有人可以指出我对
make_shared
的正确实现吗? I see that I need to use varargs to provide arguments to constructor of T. 我看到我需要使用varargs为T的构造函数提供参数。
But I don't have variadic templates available in my compiler as well. 但是我的编译器中也没有可变参数模板。
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: 如果您的编译器没有提供make_shared的实现,并且您不能使用boost,并且您不介意对象和引用计数器都缺乏单一分配优化,那么make_shared就是这样:
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& 如果您的编译器不支持r值引用,则为每个参数计数2个版本:1个const Arg&和1个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)... ));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.