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;
}
Hi, I’m trying to understand the underlying memory operations of using std::vectors. the above example is how i have used them in the past without questioning how its done.
the example2() constructor is returning an instance that goes out of scope when the addVec() function ends, so how does theVec add it whilst keeping it in scope for as long as theVec is?
and also, how come declaring a std::vector as having a constant size within a class produce a compiler error, and how can it be avoided?
When you call
theVec.push_back(example2());the vector creates a copy of the temporary instance of example2 that is passed in topush_back. This will be done using the copy constructor of the class, which the compiler will automatically generate as you have not explicitly created one.I’m not entirely sure what you are asking about declaring a
std::vectorwith a constant size.std::vectorby definition does not have a constant size. You can however construct it with an initial size by defining your constructor like this: