2016-02-02 90 views
1

首先,我創建一個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 > >]

+0

@TartanLlama的第一件事就是,我不理解的錯誤。你做? –

+0

@ PeterA.Schneider這意味着當'std :: unique_ptr '預計不能'push_back''Foo'時。 – TartanLlama

+0

@TartanLlama在正確地關注評價之後,在您發表其他評論之後,錯誤會非常有意義;-)。 –

回答

1

如果你想有一個std::vector<std::unique_ptr<Foo>>,那麼你就需要動態分配一個新的Foo對數組的每一個元素:

for(int i=0 ; i<n ; i++){ 
    vec.push_back(std::make_unique<Foo>(std::move(fooarr[i]))); 
} 
+0

爲什麼?他也可以將一個unique_ptr移動到每個元素中,這正是他想要做的,或者不是嗎?如果不是,爲什麼不呢? –

+0

@ PeterA.Schneider原始結構是一個'std :: unique_ptr',用'new []'分配給'Foo'的一個塊,並用'delete []'釋放。 OP想要改變的結構是'N'' std :: unique_ptr到'Foo'的集合。這些是完全不同的東西。 – TartanLlama

+0

啊!是的,現在我明白了,謝謝。你認爲誤解(即Foo的錯誤定義)是OP的問題嗎? (「我創建了一個Foo對象的unique_ptr數組」 - 爲什麼有人會這麼做?:-) –