#include<vector>
#include<iostream>
usingnamespace std;
struct B
{
int a;
};
class A
{
vector<B& b> pool;
void addObject()
{
B b = {10};
pool.push_back(b);
//will still the scope of b exist in vector?
//or b will be destructed?
}
}
In reference to your specific question, the vector itself will maintain all elements interior to it, but is itself beholden to scope and will be deleted upon leaving scope. Since the vector is an object of the class, its content and scope will vary with the operations performed upon and the scopes of the instanced objects. So whenever any object leaves scope it will be destroyed, its local vector will be destroyed, as will the local b, without any impact on the other vectors and b's out there.
But, really, read the link. If you don't understand scope well enough to know the answer, you should learn more because it is a wonderful, wonderful concept.
When you use push_back() you push a copy of b onto the vector. So b will go out of scope at the end of the function but the copy will remain in the vector until the vector goes out of scope.
@ Galik: not if the vector is of B&'s, which is the case here.
I'm somewhat dubious as to whether or not you can even have vectors of references. It wouldn't surprise me if you could, but it still seems like a really bad idea.