C++中显示调用构造函数和析构函数

来源:互联网 发布:python notebook 使用 编辑:程序博客网 时间:2024/06/08 06:12
#include <iostream>   using namespace std;   class A   {   public:       A()       {           cout << "Default constructor is called./r/n";       }       A(int ix)       {           cout << "Another constructor is called./r/n";       }       ~A()       {           cout << "Destructor is called./r/n";       }   };   int main()   {       A a1;          // <1>       a1.A::A();     // <2> 显示调用默认构造函数(写成a1.A()会报错)       a1.A::A(7);    // <3> 显示调用非默认构造函数(写成a1.A(7)会报错)       a1.A::~A();    // <4> 显示调用析构函数, 但是此时对象a1并没有销毁(写成a1.~A()不会报错)       // A a2();     // 这样写没报错, 但也没调用任何构造函数和析构函数.       A a3 = A();    // <5> 完整写法: A a3 = A::A();       A a4(77);      // <6>       A a5 = A(777); // <7> 完整写法: A a5 = A::A(777);       return 0;       // <8>, <9>, <10>, <11> return语句之后, 右括号之前析构函数被隐式调用. a1, a3, a4, a5对象在这里被销毁.   }  #include <iostream>using namespace std;class A{public:    A()    {        cout << "Default constructor is called./r/n";    }    A(int ix)    {        cout << "Another constructor is called./r/n";    }    ~A()    {        cout << "Destructor is called./r/n";    }};int main(){    A a1;          // <1>    a1.A::A();     // <2> 显示调用默认构造函数(写成a1.A()会报错)    a1.A::A(7);    // <3> 显示调用非默认构造函数(写成a1.A(7)会报错)    a1.A::~A();    // <4> 显示调用析构函数, 但是此时对象a1并没有销毁(写成a1.~A()不会报错)    // A a2();     // 这样写没报错, 但也没调用任何构造函数和析构函数.    A a3 = A();    // <5> 完整写法: A a3 = A::A();    A a4(77);      // <6>    A a5 = A(777); // <7> 完整写法: A a5 = A::A(777);    return 0;    // <8>, <9>, <10>, <11> return语句之后, 右括号之前析构函数被隐式调用. a1, a3, a4, a5对象在这里被销毁.} 

输出:
view plaincopy to clipboardprint?
Default constructor is called. // <1>
Default constructor is called. // <2>
Another constructor is called. // <3>
Destructor is called. // <4>
Default constructor is called. // <5>
Another constructor is called. // <6>
Another constructor is called. // <7>
Destructor is called. // <8>
Destructor is called. // <9>
Destructor is called. // <10>
Destructor is called. // <11>
Default constructor is called. // <1>
Default constructor is called. // <2>
Another constructor is called. // <3>
Destructor is called. // <4>
Default constructor is called. // <5>
Another constructor is called. // <6>
Another constructor is called. // <7>
Destructor is called. // <8>
Destructor is called. // <9>
Destructor is called. // <10>
Destructor is called. // <11>
总结:
C++中, 构造函数和析构函数可以被显示调用. 显示调用默认构造函数的语法: a.A::A();(不能写成a.A();) , 显示调用非默认构造函数的语法: a.A::A(7);(不能写成a.A(7);); 显示调用析构函数的语法: a.A::~A();(可以写成a.~A();) .
显示调用构造函数和析构函数就像调用一般的函数一样, 并不意味着创建或销毁对象;
如果构造函数中动态分配了空间, 则显示调用构造函数会造成内存泄露. 创建对象时的隐式构造函数调用已经为对象分配了动态内存. 当用创建好的对象显示调用构造函数时, 对象指向的动态内存更新显示调用时所分配的, 对象生命周期结束时析构函数所释放掉的是后一次分配的动态内存, 也就是说创建对象时隐式构造函数调用所分配的那块内存泄漏了.
如果析构函数中释放动态分配的空间, 则会造成多次释放同一内存, 会出现严重错误.

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/g5dsk/archive/2009/11/06/4775089.aspx

阅读全文
0 0
原创粉丝点击