c++ - 从函数返回一个shared_ptr

标签 c++ c++11 shared-ptr auto

我对 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 是一个指针,我想按照 Herb Sutter 的建议将其保存在 shared_ptr 中。因此,我想将 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)...);
}

关于c++ - 从函数返回一个shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12992285/

相关文章:

c++ - 检测std::shared_ptr持有原始数组(并获取其大小)

c++ - shared_ptr with map(错误error C2664)

c++ - 如果我忽略具有 shared_ptr 返回类型的函数的返回值怎么办

c++ - 通过预定义的静态地址访问寄存器是 C++ 中未定义的行为吗?

c++ - Lambda 捕获 QFile 对象

c++ - 哪些 C++ 编译器已经支持 lambda?

c++ - 无法从模板中提取 value_type

c++ - 将多态 unique_ptr 作为参数传递时发生内存泄漏

c++ - 在 C++ 中将一个巨大的文本文件 (2Gb+) 拆分为 2 个 block

c++ - C++ 中干净、功能性的脚本式错误处理