J
Jess
Hello,
If I create a temporary object using a dynamically created object's
pointer, then when the temporary object is destroyed, will the
dynamically created object be destroyed too? My guess is that it's
not destroyed, but I'm not sure.
I have the following program:
#include<iostream>
using namespace std;
class A{
public:
int x;
A():x(10){}
};
class B{
public:
A* p;
B()
(0){}
B(A* a)
(a){}
B& operator=(const B& s){
if(&s != this){
delete p;
p = s.p; //copy s's pointer, so they should point to the same
object
}
}
};
int main(){
B b;
b = new A;
cout << b.p->x << endl;
return 0;
}
In the "main" function, I first created an A object using "new", then
the A* pointer is converted to a B object, which is temporary. Then,
I assign this temporary object to "b", so that b's pointer "p" should
also point to the dynamically created A object. After this copying is
done, the temporary B object should be destroyed. I tried to output
the value of "b.p->x", and it still has the value 10. However, it may
still mean the value is garbage, i.e. the dynamically created object A
object may have been destroyed.
Thanks,
Jess
If I create a temporary object using a dynamically created object's
pointer, then when the temporary object is destroyed, will the
dynamically created object be destroyed too? My guess is that it's
not destroyed, but I'm not sure.
I have the following program:
#include<iostream>
using namespace std;
class A{
public:
int x;
A():x(10){}
};
class B{
public:
A* p;
B()
B(A* a)
B& operator=(const B& s){
if(&s != this){
delete p;
p = s.p; //copy s's pointer, so they should point to the same
object
}
}
};
int main(){
B b;
b = new A;
cout << b.p->x << endl;
return 0;
}
In the "main" function, I first created an A object using "new", then
the A* pointer is converted to a B object, which is temporary. Then,
I assign this temporary object to "b", so that b's pointer "p" should
also point to the dynamically created A object. After this copying is
done, the temporary B object should be destroyed. I tried to output
the value of "b.p->x", and it still has the value 10. However, it may
still mean the value is garbage, i.e. the dynamically created object A
object may have been destroyed.
Thanks,
Jess