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.