开发者

sending address of a variable declared on the stack?

I have a doubt concerning declaring variables, their scope, and if their address could be sent to other functions even if they are declared on the stack?


class A{
    AA a;
    void f1(){
        B b;
        aa.f2(&b);
    }
};

class AA{ B* mb; f2(B* b){ mb = b; //... } };

Afterwards, I use my AA::mb pointer in the code. So things I would like to know are following.

When the program exits A::f1() function, b variable since declared as a local variable and placed on the stack, can't be used anymore afterwards.

  1. What happens with the validity of the AA::mb pointer?

    It contains the address of the local variable which could not be available anymore, 开发者_如何学Goso the pointer isn't valid anymore?

  2. If B class is a std::<vector>, and AA::mb is not a pointer anymore to that vector, but a vector collection itself for example. I would like to avoid copying all of it's contents in AA::f2() to a member AA::mb in line mb = b. Which solution would you recommend since I can't assign a pointer to it, because it'll be destroyed when the program exits AA::f2()


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜