If I have this code:
class MyClass {... }
...
std::vector<MyClass*> myObjects;
for(int i = 0; i < 4; i++)
{
MyClass m;
myObjects.push_back(&m);
}
Is code such as this safe?
Note that I am not "newing" the objects up, but creating them on the stack, but storing pointers to them.
i.e. what (if anything) in the C++ spec is there that guarantees that it won't "re-use" (part of) the stack memory that m
occupies, either for a subsequent iteration of the loop, or for something else entirely?
It compiles fine and seems to work ok. But I'm not sure whether there is any mechanism that recognises that I have taken a pointer to the object, so don't overwrite the memory address with something else.