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,它完美地回答了我的问题。 –