c 匿名函式 普通函式 拷貝建構函式的一些研究

2021-08-19 15:20:36 字數 2582 閱讀 8103

被c++的複雜坑了一把。。

以下為初學者的一些見解吧

首先貼上實驗**:

#include using namespace std;

class test

test()

~test()

test& operator =(const test& t)

void print()

};int test::c = 1;

test get(test a)

int main()

/*輸出:

start.

this is null constructor.

print:1

this is copy constructor :1

this is get()

this is copy constructor :2

this is destory:3

this is destory:2

this is copy constructor :1

this is get()

this is copy constructor :4

this is destory:4

print:5

= :5

print:6

end.

this is destory:5

this is destory:6

process returned 0 (0x0)   execution time : 0.117 s

press any key to continue.

*/

下面一步一步來解析,看完大概就能理解了吧:)

/一

cout << "start.\n";

test t1 = test(test());

t1.print();

這裡的輸出結果是:

start.

this is null constructor.

print:1

這裡看起來像是用乙個test()匿名物件「拷貝構造」了乙個匿名物件,然後初始化了t1,實際情況是只建立了乙個物件(t1的id是1,而不是其他),說明其中進行了一次構造,並沒有呼叫拷貝構造。並且匿名物件並沒有進行析構,說明是只構建了乙個匿名物件並且該匿名物件直接「變」成了t1。

/二

test get(test a)
get(t1);
這裡輸出結果是:
this is copy constructor :1

this is get()

this is copy constructor :2

this is destory:3

this is destory:2

可以看出,傳遞進get函式時使用了一次拷貝構造,拷貝了物件(id=1)(即為t1)給物件(id=2)(即為函式的形參),然後執行get(),get的返回值被傳遞進了乙個隨機的未知空間並通過拷貝構造建立了物件(id=3)(由物件id=2複製所得),之後函式的形參(id=2)以及未知的物件(id=3)被析構。

///三

test t2 = get(t1);

t2.print();

這裡輸出結果是:

this is copy constructor :1

this is get()

this is copy constructor :4

this is destory:4

print:5

get()執行和二類似,但是在析構的時候只析構了函式的形參(id=4),在實驗二中的get()會產生的未知的物件沒有被析構,初始化的t2的id=5,並且在get結束階段拷貝建構函式只執行了一次且沒有執行賦值函式,說明get()結束階段生成的那個未知物件是通過拷貝建構函式初始化的匿名物件, 此時這個物件id=5,將t2進行了初始化。

//四

t1 = t2;

t1.print();

cout << "end.\n";

輸出結果:

= :5

print:6

end.

this is destory:5

this is destory:6

這裡將t2(id=5),通過賦值函式賦值給了t1,t1的id更新為6

隨後將程式結束,將t1,t2進行了析構。

結論:1.普通函式的形參(通過非引用傳遞)是通過拷貝建構函式建立的,並在函式結束時被析構

2.普通函式的返回值是通過形參拷貝構造了乙個匿名函式(只考慮此文章中情況)

3.多個匿名物件空參初始化的巢狀實際只會生成乙個匿名物件。

4.通過匿名物件的初始化並不會通過拷貝構造或者賦值函式

5.通過匿名物件的初始化實際上是將要初始化的物件指向了匿名函式所在的記憶體空間

ps:我只是初學者,可能有錯,理解不到位,求大佬訂正,勿噴

C 建構函式 拷貝建構函式

建構函式 class base private int m var 建構函式無返回值型別,函式名和型別相同。拷貝建構函式傳遞引數為引用。1 class base2 7 拷貝建構函式 8 base base ref m var ref m var 9 11 private 12 intm var 13...

c 建構函式和拷貝建構函式

c 中為什麼要使用建構函式?c 是從c演變過來的,c中存在的是結構體,例如 對點point struct point 但是對點的操作還要在外部使用函式來實現。c 中包括了成員屬性和成員方法,但是由於類的封裝性,不能像普通變數乙個對成員屬性就行初始化,所以使用建構函式。class point doub...

C 建構函式2 拷貝建構函式

前言 拷貝建構函式是c 中的重點之一,在這裡對其知識進行乙個簡單的總結。在c 中,對於內建型別的變數來說,在其建立的過程中用同型別的另乙個變數來初始化它是完全可以的,如 1 int value 100 2 int new value value 在變數new value建立的同時用同型別的變數val...