如果我返回文字而不是声明的std :: string会发生什么? [英] What happens if I return literal instead of declared std::string?
问题描述
假设我们有一个实用函数:
Say we have an utility function:
std::string GetDescription() { return "The description."; }
可以返回字符串文字吗?隐式创建的 std :: string
对象是否被复制了?
Is it OK to return the string literal? Is the implicitly created std::string
object copied?
我考虑过总是像这样返回它:
I thought about always returning it like this:
std::string GetDescription() { return std::move(std::string("The description.")); }
但是它当然更长,也更冗长。我们还可以假设编译器RVO将对我们有所帮助
But it's of course longer and more verbose. We could also assume that compiler RVO will help us a bit
std::string GetDescription() { return std::string("The description."); }
不过,我不知道它真正有什么作用而不是可以做到。
Yet still, I don't know what it really has to do, instead of what can it do.
推荐答案
std::string GetDescription() { return "XYZ"; }
等效于:
std::string GetDescription() { return std::string("XYZ"); }
这等效于此:
std::string GetDescription() { return std::move(std::string("XYZ")); }
表示返回 std :: string( XYZ)
是一个临时对象,则不需要 std :: move
,因为该对象仍会移动(隐式) 。
Means when you return std::string("XYZ")
which is a temporary object, then std::move
is unnecessary, because the object will be moved anyway (implicitly).
同样,当您返回 XYZ
时,则显式构造 std :: string( XYZ)
是不必要的,因为构造将始终发生(隐式)。
Likewise, when you return "XYZ"
, then the explicit construction std::string("XYZ")
is unnecessary, because the construction will happen anyway (implicitly).
所以这个问题的答案:
是否隐式创建了std :: string对象?
Is the implicitly created std::string object copied?
是。隐式创建的对象毕竟是(隐式)移动的临时对象。
is NO. The implicitly created object is after all a temporary object which is moved (implicitly). But then the move can be elided by the compiler!
所以底线是这样的:您可以编写以下代码并感到高兴:
So the bottomline is this : you can write this code and be happy:
std::string GetDescription() { return "XYZ"; }
在某些特殊情况下,返回tempObj
比返回std :: move(tempObj)
更有效(因此更好)。
And in some corner-cases, return tempObj
is more efficient (and thus better) than return std::move(tempObj)
.
这篇关于如果我返回文字而不是声明的std :: string会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!