struct hasY{
hasY()= default;
hasY(int a):y(a){cout<<"normal direct initialization"<<endl;}
hasY( hasY&another):y(another.y){cout<<"normal copy initialization"<<endl;}
int y;
};
int main(){
hasY hy = 3;
cout<<hy.y<<endl;
return 0;
}
運行結果:
normal direct initialization
3
Program ended with exit code: 0
對于 hasY hy = 3; 這一行,應該是先發生了自動型別轉化,呼叫hasY(int a)構造一個has的臨時物件,然后再用它拷貝初始化hy吧? 如果我的理解錯誤,歡迎來噴! 可是運行結果沒有呼叫拷貝建構式呢? 而且如果刪去拷貝建構式的引數里面的const,會提示No viable constructor copying variable of type 'hasY', 這同樣也說明確實用到了這個函式啊,因為生成的臨時物件只能用const hasY& 來接收。本人菜鳥一枚,希望各位大神不吝賜教,謝謝!!!
uj5u.com熱心網友回復:
因為他優化了,直接用Hy(int)初始化了hyuj5u.com熱心網友回復:
During copy initialization, the compiler is permitted (but not obligated) to skip the copy/move constructor and create the object directly. That is, the compiler is permitted to rewritestring null_book = "9-999-99999-9"; // copy initialization into
string null_book("9-999-99999-9"); // compiler omits the copy constructor
However, even if the compiler omits the call to the copy/move constructor, the copy/move constructor must exist and must be accessible (e.g., not private) at that point in the program. 終于明白啦,謝謝啊!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/69223.html
標籤:C++ 語言
