If I add elements to a vector using the code below, then at the time I call foo, the elements (automatic variables) of vec have been destroyed since the scope in which they are created ends.
std::vector<A> vec;
for (int i = 0; i < n; i++) {
A a;
vec.push_back(a);
}
foo(vec);
My question is now what the textbook solution to such a problem is
No, the elements in
vecwill be different copies ofa.However, you need to allocate the size of
vecif you want to useoperator[]or else usevec.push_back():EDIT (after question change):
Even though
push_back()takes its argument as a reference, internally it will make a copy of it. It takes it argument by reference to avoid making an unnecessary copy prior to making the copy to store internally.