从函数返回共享_ptr

Returning a shared_ptr from a function

本文关键字:ptr 共享 返回 函数      更新时间:2023-10-16

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