2011-12-13 42 views
2
class example1 
{ 
    private: 
    int i; 
public: 
    example1(){i = 1;} 
    int getI(){return i;} 
}; 

class example2 
{ 
public: 
    example2(){} 
    vector<example2> this_vector_wont_compile(3); 
    vector <example2> theVec; 
    void addVec() 
    { 
     //what's the scope of this? 
     //does push_back create a pointer 
     //to which a deep copy of the example1 instance 
     //returned by the constructor is performed? 
     theVec.push_back(example2()); 
    } 
}; 
int main() 
{ 
    example2 theExample; 
    theExample.theVec[0]; //can be accessed, instance of example1 in scope. 
    return 0; 
} 

嗨,我想了解使用std :: vectors的底層內存操作。上面的例子是我在過去如何使用它們而沒有質疑它是如何完成的。C++ std向量內容範圍

example2()構造函數在addVec()函數結束時返回一個超出範圍的實例,那麼Vec如何在添加它的同時將它保持在範圍內,只要vec是?

以及如何在一個類中聲明一個std :: vector爲一個常量大小會產生編譯器錯誤,以及如何避免它?

回答

3

當您呼叫theVec.push_back(example2());時,向量將創建example2的臨時實例的副本,並將其傳遞到push_back。這將使用該類的複製構造函數來完成,編譯器將自動生成,因爲您尚未明確創建該構造函數。

我不完全確定你在詢問關於聲明std::vector的常量大小。根據定義,std::vector沒有恆定的大小。但是,您可以通過定義像這樣的構造函數來構建初始大小:

class example2 
{ 
    example2() : theVec(10) {}; 
    std::vector<example2> theVec; 
    .... 
} 
1

addVec中的push_back操作將構造的對象複製到其內部存儲器中。原件超出範圍並被銷燬。

非編譯部分沒有意義。沒有像恆定大小的vector那樣的東西。這是std::array的用途。

+0

謝謝pmr和@obmarg,它完美地回答了我的問題。 –