将const引用返回到对象而不是副本 [英] Returning a const reference to an object instead of a copy

查看:92
本文介绍了将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& / code>?当前方法返回的副本效率不高。

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.

这篇关于将const引用返回到对象而不是副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆