J
john sun
Here is snippet code.
class B contains class A and A1 as data member. when client code execute new
B(), B construtor throw exception, ...
C++ will call destrcutor of A and A1 seperately. This is very confusing.
Since A1 and A are also on heap. How C++ track dow these member? Thanks!
#include <stdio.h>
#include <memory>
using namespace std;
class O
{
public:
O(){};
~O(){};
}
;
class A1
{
O* o;
public :
A1()
{
o=new O();
printf("in A1 ctor\n");
}
~A1()
{
delete o;
printf("in A1 dtor\n");
};
};
class A
{
public :
A(){printf("in A ctor\n");};
~A(){printf("in A dtor\n");};
};
class B
{
auto_ptr<A> a;
A1 a1;
public:
B():a(new A)
{
throw 1;
}
~B(){printf("in B dtor\n");}
};
int main(int argc, char* argv[])
{
try{
B *b=new B();
}
catch(int)
{
printf("catch block\n");
}
return 0;
}
After running a1 and a destructor will be called. This confused me. Since b
is created in heap, and a and a1 is also on heap, how come exception can
call a1 and a's destructor.
Thanks for furthermore clarifying.
Best regards to all!
class B contains class A and A1 as data member. when client code execute new
B(), B construtor throw exception, ...
C++ will call destrcutor of A and A1 seperately. This is very confusing.
Since A1 and A are also on heap. How C++ track dow these member? Thanks!
#include <stdio.h>
#include <memory>
using namespace std;
class O
{
public:
O(){};
~O(){};
}
;
class A1
{
O* o;
public :
A1()
{
o=new O();
printf("in A1 ctor\n");
}
~A1()
{
delete o;
printf("in A1 dtor\n");
};
};
class A
{
public :
A(){printf("in A ctor\n");};
~A(){printf("in A dtor\n");};
};
class B
{
auto_ptr<A> a;
A1 a1;
public:
B():a(new A)
{
throw 1;
}
~B(){printf("in B dtor\n");}
};
int main(int argc, char* argv[])
{
try{
B *b=new B();
}
catch(int)
{
printf("catch block\n");
}
return 0;
}
After running a1 and a destructor will be called. This confused me. Since b
is created in heap, and a and a1 is also on heap, how come exception can
call a1 and a's destructor.
Thanks for furthermore clarifying.
Best regards to all!