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爲一個常量大小會產生編譯器錯誤,以及如何避免它?
謝謝pmr和@obmarg,它完美地回答了我的問題。 –