sending address of a variable declared on the stack?

Posted by kobac on Stack Overflow See other posts from Stack Overflow or by kobac
Published on 2010-04-30T20:02:35Z Indexed on 2010/04/30 20:07 UTC
Read the original article Hit count: 151

Filed under:
|

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, so 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()

© Stack Overflow or respective owner

Related posts about c++

Related posts about beginner