Short answer: Yes.
Long answer: You'd have to get a pointer to a stack allocated struct and then let that struct go out of scope in order to end up with a dangling reference in your vector... but even then, you wouldn't have stored a NULL
. C and C++ pointers are simple things, and will continue to point at a memory location long after that memory location has become invalid, if your code doesn't overwrite them.
It might also be worth noting that std::vector
has a decent set of copy and move functions associated with it that will be called implicitly in this case, so the bar
vector inside the struct will also be copied along with the simple integer i
. Standard library classes tend to be quite well written, but code by other folk has no such guarantee!
Now, as regards your edit:
class Foobar {
foo m_foo;
void store(foo& f) {
this->m_foo = f;
}
}
You will still not have any problems with the foo
instance stored in m_foo
. This is because this->m_foo = f
invokes a copying operation, as m_foo
is not a variable of a reference or pointer type. If you had this instead: foo& m_foo
then you would run into difficulties because instead of copying a foo
instance you are instead copying a reference to a foo
instance, and when that instance goes out of scope, the reference is no longer valid.