tags:

views:

89

answers:

2
+5  A: 

It contains the address of the local variable which could not be available anymore, so the pointer isn't valid anymore?

Yes. It becomes a dangling pointer.

You could try vector::swap, as in:

class AA {
  B mb; // not a pointer
  f2(B* b){
    mb.swap(*b); // swap the content with b, which is just a few pointer assignments.
KennyTM
where did you get the "9 pointer assignments" from? I would assume that it would be 2 pointer assignments (one for each vector), possibly with a 3rd for temporary... but I imagine it's implemention-dependent regardless.
rmeador
@rmeador: Swapping 2 elements take 3 assignments (`temp=a;a=b;b=temp;`). There are 3 pointers in a `vector` (begin, end, capacity). At least that's how GCC implements it.
KennyTM
What if I allocated memory in `A::f1()` function with the statement `B* b = new B();`. After program exits `f1()`, the memory allocated for new `B` object is still there on the heap and can be referenced from other parts of the program, but the pointer `b` can't be used anymore, since it was on the stack ?
kobac
@kobac: The heap memory will not be removed until you explicitly `delete` it or the program ends. So the content of `b` can be used by other parts of the program. The pointer `b` itself can be copied.
KennyTM
+2  A: 

The address of a variable is a pointer. If the variable was allocated on the stack, then the pointer refers to some address on the stack. When a function returns, the next function (or some future function) that is called creates local variables in the same place on the stack. Nothing happened to the pointer, but the data pointed to has now changed.

When you allocate memory with new or malloc, you are reserving space in the heap. Nothing else should use that space until you call delete or free. Anything that may be referenced once a function returns must be allocated on the heap.

drawnonward