c++ - std::shared_ptr 和初始化列表

标签 c++ c++11 clang shared-ptr initializer-list

std::shared_ptr 构造函数的行为不符合我的预期:

#include <iostream>
#include <vector>

void func(std::vector<std::string> strings)
{
    for (auto const& string : strings)
    {
        std::cout << string << '\n';
    }
}

struct Func
{
    Func(std::vector<std::string> strings)
    {
        for (auto& string : strings)
        {
            std::cout << string << '\n';
        }
    }
};

int main(int argc, const char * argv[])
{

    func({"foo", "bar", "baz"});
    Func({"foo", "bar", "baz"});
    //auto ptr = std::make_shared<Func>({"foo", "bar", "baz"}); // won't compile.
    //auto ptr = std::make_shared<Func>{"foo", "bar", "baz"}; // nor this.
    return 0;
}

我做错了什么还是编译器?编译器是:

$ clang++ --version Apple clang 4.0 版(tags/Apple/clang-421.0.57)(基于 LLVM 3.1svn)

编辑:shared_ptr 而不是 make_shared。

这是错误:

make -k 
clang++ -std=c++11 -stdlib=libc++    main.cc   -o main
main.cc:28:18: error: no matching function for call to 'make_shared'
      auto ptr = std::make_shared<Func>({"foo", "bar", "baz"});
                 ^~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/c++/v1/memory:4621:1: note: candidate function not viable:
     requires 0 arguments, but 1 was provided
make_shared(_Args&& ...__args)
^
1 error generated.

最佳答案

试试这个:

auto ptr = std::make_shared<Func>(std::initializer_list<std::string>{"foo", "bar", "baz"});

Clang 不愿意推断 {"foo", "bar", "baz"} 的类型。我目前不确定这是否是该语言应该工作的方式,或者我们是否正在查看编译器错误。

关于c++ - std::shared_ptr 和初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11820981/

相关文章:

c++ - 我们可以在 C++14 中省略 std::array 的双括号吗?

C++11模板别名作为模板模板参数导致不同的类型?

c++ - 如何在 gcc 或 clang 中启用从 int 到 int64_t 的转换警告

C++ 程序中函数的 Python 绑定(bind)

c# - 在 C#/C++ 之间编码复杂结构

c++ - 如何使用 nsCOMPtr 正确调用 do_QueryInterface

eclipse - Nsight Eclipse Cuda + opencv

c++ - MIPS 上 C++ 和汇编代码的微架构分析

c++ - 作为模板参数的结构数组

c - 如何使生成的自动工具 ./configure 强制 C11 的 _Generic 的可用性?