假设我们有一个实用功能:
std::string GetDescription() { return "The description."; }
Run Code Online (Sandbox Code Playgroud)
可以返回字符串文字吗?是否std::string复制了隐式创建的对象?
我想总是这样回来:
std::string GetDescription() { return std::move(std::string("The description.")); }
Run Code Online (Sandbox Code Playgroud)
但它当然更长,更冗长.我们还可以假设编译器RVO会对我们有所帮助
std::string GetDescription() { return std::string("The description."); }
Run Code Online (Sandbox Code Playgroud)
然而,我仍然不知道什么是真正有做的,而不是什么可以它来做.
Naw*_*waz 13
std::string GetDescription() { return "XYZ"; }
Run Code Online (Sandbox Code Playgroud)
相当于:
std::string GetDescription() { return std::string("XYZ"); }
Run Code Online (Sandbox Code Playgroud)
这相当于这个:
std::string GetDescription() { return std::move(std::string("XYZ")); }
Run Code Online (Sandbox Code Playgroud)
意味着当您返回std::string("XYZ")这是一个临时的对象,则std::move是不必要的,因为对象将移动反正(隐含的).
同样,当你返回时"XYZ",显式构造std::string("XYZ")是不必要的,因为构造将无论如何(隐式地)发生.
所以这个问题的答案是:
是否复制了隐式创建的std :: string对象?
没有.隐式创建的对象毕竟是一个临时移动的对象(隐式).但是编译器可以省略此举!
最重要的是:您可以编写此代码并感到高兴:
std::string GetDescription() { return "XYZ"; }
Run Code Online (Sandbox Code Playgroud)
在某些角落情况下,return tempObj效率更高(因而更好)return std::move(tempObj).
| 归档时间: |
|
| 查看次数: |
374 次 |
| 最近记录: |