構(gòu)造函數(shù)的使用位置與特點(diǎn)

構(gòu)造了9個(gè)例子,基本應(yīng)該覆蓋了所有情況,其中編譯器如何進(jìn)行優(yōu)化的,也做了部分探索。

普通構(gòu)造函數(shù)

造出來(lái)什么樣就什么樣。

拷貝構(gòu)造函數(shù)

1.用同類(lèi)初始化。
2.傳入?yún)?shù)。
3.返回參數(shù)。

優(yōu)化特征 NRV(在測(cè)試點(diǎn)9中,返回的參數(shù)==傳入的參數(shù),所以同時(shí)存在 2、 3,兩次拷貝構(gòu)造函數(shù)的調(diào)用)

返回的參數(shù)!=傳入的參數(shù)-->不調(diào)用拷貝構(gòu)造函數(shù)(利用內(nèi)部的普通構(gòu)造函數(shù)的值即可)

賦值構(gòu)造函數(shù)

已經(jīng)存在的類(lèi),用另一個(gè)類(lèi)進(jìn)行處理。
PS:說(shuō)是賦值構(gòu)造函數(shù),實(shí)際上就是clone函數(shù)。所以在傳參的時(shí)候

#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <map>
#include <stack>
using namespace std;

// 拷貝構(gòu)造函數(shù)
// 賦值構(gòu)造函數(shù)
// 構(gòu)造函數(shù)
// 析構(gòu)函數(shù)
class Solution{
public:
    Solution(){
        cout << "默認(rèn)構(gòu)造函數(shù)" << endl;
    }
    Solution(const Solution &rhs){
        data = rhs.data;
        cout << "拷貝構(gòu)造函數(shù)" << endl;
    }
    Solution& operator=(const Solution &rhs){
        data = rhs.data;
        cout << "賦值構(gòu)造函數(shù)" << endl;
        return *this;
    }
    ~Solution(){
        // cout << data << endl;
        cout << "析構(gòu)函數(shù)" << endl;
    }
public:
    string data;
};

// 用于測(cè)試傳入?yún)?shù)
void my_func1(Solution temp){
    ;
}

// 用于測(cè)試返回值
Solution my_func2(){
    Solution other;
    other.data = "func2";
    return other;
}

Solution my_func3(Solution &s){
    return s;
}

Solution my_func4(Solution s){
    return s;
}

int main()
{
    cout << "測(cè)試1:默認(rèn)構(gòu)造函數(shù)" << endl;
    Solution a;
    cout << "測(cè)試2:拷貝構(gòu)造函數(shù)測(cè)試點(diǎn)1,顯式初始化" << endl;
    Solution b(a);
    cout << "無(wú)用測(cè)試:默認(rèn)構(gòu)造函數(shù)" << endl;
    Solution c;
    cout << "測(cè)試3:賦值構(gòu)造函數(shù)" << endl;
    c = b;
    c.data = "原來(lái)的c";

    cout << "測(cè)試4:拷貝構(gòu)造函數(shù)測(cè)試點(diǎn)2,函數(shù)傳入?yún)?shù)" << endl;
    my_func1(c);
    cout << "測(cè)試5:拷貝構(gòu)造函數(shù)測(cè)試點(diǎn)3,返回值。" << endl;
    my_func2();
    cout << "測(cè)試6:拷貝構(gòu)造函數(shù)測(cè)試點(diǎn)4,返回值,返回到一個(gè)未初始化的值。(結(jié)果是賦值構(gòu)造函數(shù))" << endl;
    Solution d = my_func2();
    cout << "測(cè)試7:拷貝構(gòu)造函數(shù)測(cè)試點(diǎn)5,返回值,返回到一個(gè)已初始化的值,增加一個(gè)賦值構(gòu)造函數(shù)" << endl;
    c = my_func2();
    cout << "測(cè)試8:傳入引用,返回(以引用為結(jié)果的非引用)。調(diào)用拷貝構(gòu)造函數(shù)。" << endl;
    my_func3(c);
    cout << "測(cè)試9:傳入正常,返回正常。調(diào)用拷貝構(gòu)造函數(shù)(兩次)(傳入一次、傳出一次)。" << endl;
    my_func4(c);
    cout << "結(jié)束" << endl;
    return 0;
}
測(cè)試結(jié)果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容