Quote:Original post by Gink
This code shouldnt work correctly, right? The objects stored at the adress are destroyed when the loop is over so why does this still function as normal?
b is derived class of A.vector<A*> vec; for(int x=0; x < 10; x++){ B ob; vec.push_back(&ob); } vec[5]->getv();
Technically it should work yes but that doesn't mean it's correct...
1. At the beginning of each iteration the constructor for "ob" is called. In the example this is before vec.push_back() is called.
2. At the end of each iteration the destructor of ob is called. In the example this is after vec.push_back() is called.
3. After all iterations have completed it's very likely that all elements of "vec" point to the same memory address. Changing one element changes them all.
4. After you leave the function (and especially during/after the call to another function) The memory occupied by "ob" is corrupt. If it has a vtable it's gone bye bye.
So why does it function as normal?
1. 'vec' has not been destroyed yet so it still contains all elements you added to it (in this case a pointer an object).
2. the memory pointed to by '&ob' is still valid (local - on the stack).
3. You havn't actually tried accessing any virtual functions of the objects you added to 'vec'. If you do changes are an exception will be encountered - especially if they are vtables.
Unless you are doing something that is not syntactically correct don't expect the compiler to complain about it or even alert you to it. It's really not the job of the compiler to second guess what your intentions are....that job belongs to lint++