相关疑难解决方法(0)

C++ get方法 - 按值或按引用返回

我提出了一个非常简单的问题,但遗憾的是我自己无法找到答案.

假设我有一些保存设置的数据结构,就像设置图一样.我有一个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

在这种情况下你会选择什么?为什么?

c++ reference return-value return-value-optimization

6
推荐指数
2
解决办法
1万
查看次数