首先,我創建一個unique_ptr Foo對象數組。 然後我將對象移動到一個向量中,如下面的代碼所示。 但是這段代碼不能編譯。 另一個問題是因爲對象是使用新運算符的數組版本分配的。 如果發生異常並且程序必須在將對象移回到unique_ptr數組之前終止,會發生什麼? 在這種情況下,vector vec將使用delete操作符來銷燬它的內容,而不是delete操作符的數組版本? 我們如何解決這類問題?將對象從unique_ptr數組移動到矢量
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: In function 'int main()': main.cpp:47: error: no matching function for call to '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: note: candidates are: 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: note: void std::vector<_Tp, _Alloc>::push_back(_Tp&&) [with _Tp = std::unique_ptr >, _Alloc = std::allocator > >]
@TartanLlama的第一件事就是,我不理解的錯誤。你做? –
@ PeterA.Schneider這意味着當'std :: unique_ptr'預計不能'push_back''Foo'時。 –
TartanLlama
@TartanLlama在正確地關注評價之後,在您發表其他評論之後,錯誤會非常有意義;-)。 –