从初始化程序列表初始化unique_ptrs的容器失败,使用GCC 4.7 [英] Initializing container of unique_ptrs from initializer list fails with GCC 4.7
问题描述
我试图以一种方式初始化 std :: vector< std :: unique_ptr< std :: string>>
a href =http://www.stroustrup.com/C++11FAQ.html#std-unique_ptr> Bjarne Stroustrup的C ++ 11常见问题:
using namespace std;
矢量< unique_ptr< string>> vs {new string {Doug},new string {Adams}}; // failed
unique_ptr< string> ps {new string {42}}; // OK
我看不到这个语法失败的原因。这种初始化容器的方式有什么问题吗?
编译器错误消息是巨大的;我发现的相关细分如下:
/usr/lib/gcc-snapshot/lib/gcc/i686-linux-gnu/4.7 .0 /../../../../ include / c ++ / 4.7.0
/bits/stl_construct.h:77:7:错误:没有匹配函数调用
'std :: unique_ptr< std :: basic_string< char> > :: unique_ptr(std :: basic_string< char>&)'
code> explicit 。因此,您不能使用
new string {foo}
隐式创建一个。它需要像 unique_ptr< string> {new string {foo}}
。 我们到这个
矢量< unique_ptr< string> vs {
unique_ptr< string> {new string {Doug}},
unique_ptr< string> {new string {Adams}}
};
但是,如果其中一个构造函数失败,它可能会泄露。使用 make_unique
更安全:
矢量< unique_ptr< string>> vs {
make_unique< string>(Doug),
make_unique< string>(Adams)
};
但是... initializer_list
副本, unique_ptr
不可复制。这是真的烦人的初始化列表。您可以黑客攻击,或者调用 emplace_back
。
如果你实际上用智能指针来管理 string
,这不只是示例,你可以做得更好:只要使一个向量< string>
。 std :: string
已经处理它使用的资源。
I am trying to initialise an std::vector<std::unique_ptr<std::string>>
in a way that is equivalent to an example from Bjarne Stroustrup's C++11 FAQ:
using namespace std;
vector<unique_ptr<string>> vs { new string{"Doug"}, new string{"Adams"} }; // fails
unique_ptr<string> ps { new string{"42"} }; // OK
I can see no reason why this syntax should fail. Is there something wrong with this way of initializing the container?
The compiler error message is huge; the relevant segment I find is below:
/usr/lib/gcc-snapshot/lib/gcc/i686-linux-gnu/4.7.0/../../../../include/c++/4.7.0 /bits/stl_construct.h:77:7: error: no matching function for call to
'std::unique_ptr<std::basic_string<char> >::unique_ptr(std::basic_string<char>&)'
What is the way to fix this error ?
unique_ptr
's constructor is explicit
. So you can't create one implicitly with from new string{"foo"}
. It needs to be something like unique_ptr<string>{ new string{"foo"} }
.
Which leads us to this
vector<unique_ptr<string>> vs {
unique_ptr<string>{ new string{"Doug"} },
unique_ptr<string>{ new string{"Adams"} }
};
However it may leak if one of the constructors fails. It's safer to use make_unique
:
vector<unique_ptr<string>> vs {
make_unique<string>("Doug"),
make_unique<string>("Adams")
};
But... initializer_list
s always perform copies, and unique_ptr
s are not copyable. This is something really annoying about initializer lists. You can hack around it, or fallback to initialization with calls to emplace_back
.
If you're actually managing string
s with smart pointers and it's not just for the example, then you can do even better: just make a vector<string>
. The std::string
already handles the resources it uses.
这篇关于从初始化程序列表初始化unique_ptrs的容器失败,使用GCC 4.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!