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: 170
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.
- 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? - If
B
class is astd::<vector>
, andAA::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 inAA::f2()
to a memberAA::mb
in linemb = b
. Which solution would you recommend since I can't assign a pointer to it, because it'll be destroyed when the program exitsAA::f2()
© Stack Overflow or respective owner