从函数返回共享_ptr
Returning a shared_ptr from a function
我是C 11的新手,'仍然非常尝试扩展。我发现auto
关键字非常方便,尤其是在处理模板变量时。这意味着给定
template<typename ... Types>
struct Foo
{
};
template<typename ... Types>
Foo<Types ...>* create( Types ... types ... )
{
return new Foo<Types ...>;
}
我现在可以进行分配
auto t1 = create( 'a' , 42 , true , 1.234 , "str" );
而不是
Foo<char, int, bool, double , const char*>* t2 = create( 'a' , 42 , true , 1.234 , "str" );
现在的问题是,因为t1
是一个指针,所以我想在shared_ptr
中握住它,因为Herb Sutter推荐。因此,我想将create()
的返回值存储在shared_ptr
中,而不必命名模板参数类型,例如t2
。
避免一起使用原始指针。使用std::make_shared
和make_unique
(标准中不正确)而不是new
。然后auto
可以很好地工作。例如
template <typename ...Args>
auto create(Args&&... args)
-> std::shared_ptr<Foo<typename std::decay<Args>::type...>>
{
return std::make_shared<Foo<typename std::decay<Args>::type...>>(
std::forward<Args>(args)...);
}
这太长了,无法将其作为评论。因此,我将其发布在这里。此外,这可能是一个答案。
@nosid为什么不以下内容。它不那么令人费解。
template<typename ... Types>
struct Foo
{
Foo( Types ... types ... ) : m_data( types ...)
{
}
std::tuple<Types...> m_data;
};
template<typename ... Types>
std::shared_ptr<Foo<Types ...> > create( Types ... types ... )
{
return std::make_shared<Foo<Types ...> >( types ... );
}
相关文章:
- 为共享 ptr 向量实现复制 c'tor?
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何控制共享 ptr 引用计数?
- 这是MSVC 2013中具有共享PTR的单例的正确实现吗?
- 如何从原始 ptr 递增共享 ptr 的计数
- 使用 void 指针:void **ptr.. 如何修改共享内存的值?
- 唯一/共享 ptr 用于在数组超出范围后自动删除阵列
- 如何从集合中删除共享的 PTR 元素
- C 在多个引用上共享PTR发布
- 共享PTR地图与LLDB漂亮的打印机
- 使针对特定托管对象的所有共享 ptr 失效
- c++在没有虚拟析构函数的多态性中共享ptr
- 我如何在void*和boost共享ptr之间切换
- gcc共享ptr副本分配实现
- C++11共享Ptr,共享相同的参考计数器
- 为什么这个显式析构函数会导致共享ptr中的内存损坏
- 在联合中共享ptr
- 从数组的共享ptr访问共享ptr
- 添加对共享ptr的引用会增加引用计数吗?
- 如何在不使代码庞大的情况下处理共享/弱ptr ?