比較顯式調用建構函式和解構函式

來源:互聯網
上載者:User

1.首先看如下的代碼,顯式調用解構函式:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

class MyClass
{
public:
    MyClass()
    {
        n_ = 1;
        cout << "Constructors" << endl;
    }
    ~MyClass()
    {
        cout << "Destructors" << endl;
    }
    void display()
    {
        cout << n_ << endl;
    }
private:
    int n_;
};

int main (void)
{
    MyClass *pMyClass = new MyClass;
    pMyClass->~MyClass();
    delete pMyClass;
    return 0;
}

輸出為:

Constructors

Destructors

Destructors


證實了一些說法:

new的時候,其實做了兩件事,

一是:調用malloc分配所需記憶體(實際上是調用operator new),二是:調用建構函式。

delete的時候,也是做了兩件事,

一是:調用析造函數,二是:調用free釋放記憶體(實際上是調用operator delete)。

這裡只是為了示範,正常情況下解構函式只會被調用一次,如果被調用兩次,而解構函式內有delete的操作,會導致記憶體釋放兩次的錯誤。

2. 接著再看:顯式調用建構函式(第一種方式):

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>

using namespace std;

class MyClass
{

public:

    MyClass()
    {
        n_ = 1;

        cout << "Constructors" << endl;
    }

    ~MyClass()
    {
        cout << "Destructors" << endl;
    }

    void display()
    {
        cout << "n=" << n_ << endl;
    }

private:

    int n_;

};

int main (void)
{

    MyClass *pMyClass = (MyClass *)malloc(sizeof(MyClass));

    pMyClass->MyClass::MyClass(); //第一種方式

    pMyClass->display();

    free(pMyClass); // 不能用delete,對應malloc,不會調用解構函式

    return 0;
}

輸出為:

Constructors

n=1


3.顯示調用建構函式(第二種方式):placement new 

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

using namespace std;

class MyClass
{
public:
     MyClass()
    {
        n_ = 1;
        cout << "Constructors" << endl;
    }

    ~MyClass()
    {
        cout << "Destructors" << endl;
    }

    void display()
    {
        cout << "n=" << n_ << endl;
    }

private:

    int n_;
};

int main (void)
{
    char tmp[10];
    MyClass *pMyClass = new (tmp) MyClass; // placement new 用法
    pMyClass->display();
    pMyClass->~MyClass(); // 不是堆上的記憶體,不能用delete 
    return 0;
}

Constructors

n=1

Destructors

placement new的作用就是:建立對象(調用該類的建構函式)但是不分配記憶體,而是在已有的記憶體塊上面建立對象。用於需要反覆建立並刪除的對象上,可以降低分配釋放記憶體的效能消耗。


參考:http://www.cnblogs.com/fangyukuan/archive/2010/08/28/1811119.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.