i am a newbie. like to understand why "p=&a" does not work. thank you.
class A{
int *p;
public:
A(int a){p=new int; p=&a;}
~A(){delete p;}
};
int main(void){
A B(11);
}
i am a newbie. like to understand why "p=&a" does not work. thank you.
class A{
int *p;
public:
A(int a){p=new int; p=&a;}
~A(){delete p;}
};
int main(void){
A B(11);
}
A(int a){p=new int; p=&a;}
first of all allocates an int
to the pointer p
, then secondly trashes that pointer value with the address of the temporary a
.
So you end up with a dangling pointer and a memory leak! The behaviour of your destructor will be undefined.
*p = a
is fine, since you are dereferencing p
. Although that said, using bare pointers as class members causes problems with copying instances of your object. It's best avoided.