0

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.

BenTaylor
  • 414
  • 4
  • 12
  • 1
    It only seems to work. Do something with your objects after the loop and they should be garbage. `MyClass` is created in the `scope` of the loop, so, destroyed immediately per each iteration. – lakeweb Dec 22 '18 at 17:03
  • See also [What is a dangling pointer?](https://stackoverflow.com/questions/17997228/what-is-a-dangling-pointer) – Cornstalks Dec 22 '18 at 17:03
  • 1
    Read the answer of the duplicate it has a great analogy that explains why "seems to work" is not good enough. – Slava Dec 22 '18 at 17:04
  • 1
    As-is, your code is actually okay. But that's only because you don't attempt to do anything interesting with `myObjects`. If you try to dereference or use any of those (dangling) pointers, that's undefined behavior. – Cornstalks Dec 22 '18 at 17:07
  • ***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*** It will likely use the same memory. – drescherjm Dec 22 '18 at 17:13
  • If you examine the address of each `m` that you store in the vector they are likely the same. Ask yourself why. – doug Dec 22 '18 at 21:36
  • @doug - No, they weren't the same though - that's the only reason I felt the need to ask the question. If they'd been the same, it was obviously unsafe. That's why I said it 'seemed to work', so I wondered if there was something that was recognising that I was storing the pointers and thus putting each one in a different piece of memory. – BenTaylor Dec 23 '18 at 18:48
  • Odd. If I look at `m[0], m[1]`, etc. they each are pointers with the same address hence all the 'm's point to the exact same object. It's destructed and reconstructed each pass in the same place. Compilers don't have to do that in the same place but I'm not aware of any that don't. What compiler are you using? – doug Dec 23 '18 at 21:12

0 Answers0