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::vector 的底层内存操作。上面的例子是我过去如何使用它们的,而不质疑它是如何完成的。
example2() 构造函数返回一个实例,该实例在 addVec() 函数结束时超出范围,那么 theVec 如何添加它,同时将其保持在与 theVec 一样长的范围内?
另外,为什么在类中声明 std::vector 具有常量大小会产生编译器错误,以及如何避免?
最佳答案
当您调用 theVec.push_back(example2());
时, vector 会创建 example2 临时实例的拷贝,并将其传递给 push_back
。这将使用类的复制构造函数来完成,当您没有显式创建复制构造函数时,编译器将自动生成该构造函数。
我不完全确定您在声明具有常量大小的 std::vector
时要问什么。 std::vector
根据定义,没有恒定的大小。但是,您可以通过像这样定义构造函数来构造它的初始大小:
class example2
{
example2() : theVec( 10 ) {};
std::vector< example2 > theVec;
....
}
关于C++ std vector 内容范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8489636/