Yip*_*Yay 6 c++ reference return-value return-value-optimization
我提出了一个非常简单的问题,但遗憾的是我自己无法找到答案.
假设我有一些保存设置的数据结构,就像设置图一样.我有一个GetValue(const std::string& name)方法,返回相应的值.
现在我想弄明白 - 什么样的回报价值方法会更好.显而易见的意思是让我的方法表现得像
std::string GetValue(const std::string& name) const
Run Code Online (Sandbox Code Playgroud)
并返回对象的副本,并依赖于RVO的性能含义.
另一个意味着制作两种方法
std::string& GetValue(...)
const std::string& GetValue(...) const
Run Code Online (Sandbox Code Playgroud)
这通常意味着复制代码或使用一些邪恶的常量强制转换来使用其中一个例程两次.
#Q在这种情况下你会选择什么?为什么?
其实我可能会用:
std::string GetValue(const std::string& name) const;
// or
const std::string* GetValue(const std::string& name) const;
void SetValue(std::string name, std::string value);
Run Code Online (Sandbox Code Playgroud)
塞特首先:
SetValue允许编译器进行一些无法通过const-reference传递的优化,在Dave Abrahams的一篇文章中已经解释过,"想要速度?通过值传递".Setter通常更好,因为你可以检查所设置的值,而使用普通引用你不能保证调用者不会对数据做任何愚蠢的事情.对于吸气剂:
std::wstring因为您需要UTF-8中的某些设置...