沒有呼叫拷貝建構函式卻提示呼叫了隱式的拷貝建構函式?

時間 2021-06-01 03:43:27

1樓:Furion W

在newNode.ptr = new Node(std::move(data))中,Node的初始化列表裡發生了這次拷貝構造

data(std::move(std::make_shared(std::

move(data_)))).

make_shared - C++ Reference

Allocates and constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr that owns and stores a pointer to it (with a use count of 1).make_shared將「move後過的型別為T&&的變數」傳遞給了T(亦即你的Test)的建構函式。

1. 如果T類沒有移動建構函式(move ctor),它的拷貝建構函式(copy ctor)會被呼叫

#include

#include

structTT

(constT&

t)// T(const T&& t)

};int

main

()執行:

test c++ rvalue.cpp -std=c++11 -o rvalue

test ./rvalue

T()sp1 begin:

T()sp2 begin:

T(const T&

)sp3 begin:

T(const T&

)2. 如果T有移動建構函式(把T定義中的注釋取消),在構造sp3時移動建構函式將被呼叫(而不是拷貝構造):

test c++ rvalue.cpp -std=c++11 -o rvalue

test ./rvalue

T()sp1 begin:

T()sp2 begin:

T(const T&

)sp3 begin:

T(const T&&)

C 中,既然有了建構函式, 那麼拷貝建構函式存在的意義是?

白白小白 copy constructor 建立物件的時候,用同一類的物件對它進行初始化的時候會自動呼叫拷貝建構函式。Aa Ab a 或者傳參Ab f b 或者返回值是物件Af 語法 public A constA a 我們首先希望傳參的時候不會對原來的物件產生修改,所以使用了const型別 避免迴...

C 如何實現自動呼叫建構函式?

夏洋 如果你用C 11的話,直接這麼寫就行了 class UserClass Base 甚至你想只寫成一句 DefValues i,j,k 也是有辦法的。例如 define FIRST a,a define SECOND a,b,b define EMPTY define DEFER1 m m EM...

建構函式不能是虛函式

ylq 建構函式不是不能是虛函式,而是完全沒意義。c 在編譯期間就能確定你要建立的物件的具體型別,而這個具體型別包含了什麼,繼承了什麼在編譯期間也是明確的,所以要構造什麼也都是明確的,根本沒必要存在虛建構函式。虛函式的存在是因為編譯期間沒法確定具體呼叫物件,才會有虛函式,虛函式表這麼個東西。 雞賊軒...