[英]Why are moves more expensive than passing by const&?
我即將在其生命周期結束之前將一些對象傳遞給構造函數。
int main(){
//I wanted to avoid short string optimization in this example.
const std::string a(25,"a");
const std::string b(25,"b");
const std::string c(25,"c");
Foo f{a,b,c};
}
我為Foo的構造函數考慮了兩個選項。
const&
(調用字符串的副本構造函數):
Foo(const std::string & a,
const std::string & b,
const std::string & c)
:a(a)
,b(b)
,c(c)
{}
std::move
(調用字符串的move構造函數):
Foo(std::string a,
std::string b,
std::string c)
:a(std::move(a))
,b(std::move(b))
,c(std::move(c))
{}
在-01
gcc 7
上使用-01
,我得到以下結果:
+-------------+-----------------------+
| constructor | assembly instructions |
+-------------+-----------------------+
| const& | 192 |
| move | 264 |
+-------------+-----------------------+
為什么使用const&
less指令?
我認為此舉比通過復制構造函數創建新字符串要便宜。
將變量作為構造函數參數傳遞的經驗法則是什么
這些爭論的壽命何時結束?
您沒有在調用move構造函數。 您的參數字符串是const。 因此,當對它們使用std::move
時,結果為const std::string&&
。 這不會調用move構造函數,后者的簽名采用std::string&&
。
如果編譯器沒有為main調用構造函數的特殊版本,則main
仍在調用帶有簽名Foo(std::string a, std::string b, std::string c);
的函數Foo(std::string a, std::string b, std::string c);
除非它內聯,否則gcc會對其進行克隆而實際上以不同的方式傳遞args,否則函數定義中的代碼將無法更改其調用方式。
想象一下,構造函數定義在一個單獨的文件中,而在編譯main
,它甚至是不可見的,只有原型。 這類似於僅使用-O1
進行編譯所得到的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.