返回对对象的 const 引用而不是副本

2022-01-23 00:00:00 constants c++

在重构一些代码时,我遇到了一些返回 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.

相关文章