Returning a const reference to an object instead of a copy(返回对对象的 const 引用而不是副本)
问题描述
在重构一些代码时,我遇到了一些返回 std::string 的 getter 方法.例如这样的事情:
Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:
class foo
{
private:
std::string name_;
public:
std::string name()
{
return name_;
}
};
当然,getter 会更好地返回 const std::string&
?当前方法正在返回一个效率不高的副本.返回一个 const 引用会导致任何问题吗?
Surely the getter would be better returning a const std::string&
? The current method is returning a copy which isn't as efficient. Would returning a const reference instead cause any problems?
推荐答案
这可能导致问题的唯一方法是调用者存储引用,而不是复制字符串,并在对象被销毁后尝试使用它.像这样:
The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed. Like this:
foo *pFoo = new foo;
const std::string &myName = pFoo->getName();
delete pFoo;
cout << myName; // error! dangling reference
但是,由于您现有的函数返回一个副本,那么您将不要破坏任何现有的代码.
However, since your existing function returns a copy, then you would not break any of the existing code.
现代 C++(即 C++11 及更高版本)支持 返回值优化,让按值返回的东西不再被讨厌.仍然应该注意按值返回非常大的对象,但在大多数情况下应该没问题.
Modern C++ (i. e. C++11 and up) supports Return Value Optimization, so returning things by value is no longer frowned upon. One should still be mindful of returning extremely large objects by value, but in most cases it should be ok.
这篇关于返回对对象的 const 引用而不是副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回对对象的 const 引用而不是副本


基础教程推荐
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01