簡體   English   中英

用於賦值的參數化構造函數

[英]Parameterized constructor for assignment

我注意到一些我在參數化構造函數中無法理解的行為。 鑒於以下計划:

#include <iostream>
using namespace std;

class A {
public:
    int x;

    A() {}

    A(int i) : x(i){
        cout << "A\n";
    }
    ~A(){
        cout << "dA\n";
    }

};

int main(){
    A p;
    p = 3;
    cout << p.x << endl;
    p = 5;
    cout << p.x << endl;
    return 0;
}

我得到輸出:

A
dA
3
A
dA
5
dA

這意味着using =觸發參數化構造函數,銷毀它所調用的對象並創建一個新對象。 我無法理解這種行為,我無法在標准中找到答案(我確信它存在於某個地方,但可能以復雜的方式陳述)。 有人可以幫我解釋一下嗎?

有一個聲明

p = 3;

你真正在做的是

p = A(3);

這實際上轉化為

p.operator=(A(3));

A(3)創建的臨時A對象當然需要被破壞,畢竟它是暫時的

對象p本身不會被賦值破壞。

您可能正在尋找的短語是“隱式轉換”。

如果添加復制構造函數和賦值運算符,然后為每個對象提供唯一的ID,則更容易看到事情的進展:

int counter = 0;

class A {
public:
    int id;

    A(): id(++counter) {cout << "A(): " << id << "\n";}

    A(int i) : id(++counter) {cout << "A(" << i << "): " << id << "\n";}

    // Don't copy the id.
    // (This isn't used anywhere, but you can't see that it's not used unless it exists.)
    A(const A& a) : id(++counter) {cout << "A(" << a.id << "): " << id << "\n";}

    // Don't copy the id here either.
    A& operator=(const A&a) {cout << id << " = " << a.id << "\n"; return *this;}

    ~A(){cout << "destroy: " << id << "\n";}
};

int main(){
    A p;
    cout << "p is " << p.id << "\n";
    p = 3;
    cout << "p is " << p.id << "\n";    
    p = 5;
    cout << p.id << "\n";
}

輸出:

A(): 1
p is 1
A(3): 2
1 = 2
destroy: 2
p is 1
A(5): 3
1 = 3
destroy: 3
1
destroy: 1

如您所見,參數化構造函數用於創建一個臨時對象,其值可以分配給p ,之后會立即銷毀該臨時對象。
你也可以看到p是活着的,直到最后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM