首先,我创建一个Foo对象的unique_ptr数组 . 然后我将对象移动到矢量,如下面的代码所示 . 但是这段代码没有编译 . 另一个问题是,因为对象是使用new运算符的数组版本分配的 . 如果发生异常并且在将对象移回unique_ptr数组之前程序必须提前终止会发生什么?在这种情况下,向量vec将使用delete运算符销毁其内容,而不是删除运算符的数组版本?我们如何解决这类问题?
class Foo
{
public:
int id;
Foo(){};
};
int main()
{
int n = 10;
std::unique_ptr<Foo []> fooarr(new Foo[n]);
std::vector<std::unique_ptr<Foo>> vec;
for( int i=0 ; i<n ; i++ ){
fooarr[i].id = i;
}
for( int i=0 ; i<n ; i++ ){
vec.push_back( std::move(fooarr[i]) );
}
//then move back the Foo objects from vec to fooarr
}
这是我从编译器得到的 .
main.cpp:在函数'int main()'中:main.cpp:47:错误:没有匹配函数用于调用'std :: vector>,std :: allocator >>> :: push_back(Foo)'/ usr / lib / gcc / x86_64-redhat-linux / 4.4.7 /../../../../ include / c /4.4.7/bits/stl_vector.h:733:注意:候选人是:void std :: vector <_Tp,_Alloc> :: push_back(const _Tp&)[with Tp = std :: unique_ptr>, Alloc = std :: allocator >>] /usr/lib/gcc/x86_64-redhat-linux/4.4 . 7 /../../../../ include / c /4.4.7/bits/stl_vector.h:746:注意:void std :: vector <_Tp,_Alloc> :: push_back(_Tp &&)[with Tp = std :: unique_ptr>, Alloc = std :: allocator >>]
1 回答
如果你想要
std::vector<std::unique_ptr<Foo>>
那么你需要为数组的每个元素动态分配一个新的Foo
: