C++ get 方法 - 按值或按引用返回 [英] C++ get method - returning by value or by reference

查看:80
本文介绍了C++ get 方法 - 按值或按引用返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个非常简单的问题,但不幸的是我自己想不出答案.

I've go a very simple question, but unfortunately I can't figure the answer myself.

假设我有一些数据结构来保存设置并充当设置映射.我有一个 GetValue(const std::string& name) 方法,它返回相应的值.

Suppose I've got some data structure that holds settings and acts like a settings map. I have a GetValue(const std::string& name) method, that returns the corresponding value.

现在我想弄清楚 - 什么样的返回值方法会更好.显而易见的方法是让我的方法像

Now I'm trying to figure out - what kind of return-value approach would be better. The obvious one means making my method act like

std::string GetValue(const std::string& name) const

并返回对象的副本,并在性能意义上依赖 RVO.

and return a copy of the object and rely on RVO in performance meanings.

另一种意味着制作两种方法

The other one would mean making two methods

std::string& GetValue(...)
const std::string& GetValue(...) const

这通常意味着重复代码或使用一些邪恶的常量强制转换来两次使用这些例程之一.

which generally means duplicating code or using some evil constant casts to use one of these routines twice.

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

推荐答案

实际上我可能会使用:

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);

先发:

  • SetValue 中按值传递允许编译器进行一些无法通过按常量引用进行的优化,Dave Abrahams 在一篇文章中对此进行了解释,想要速度?通过价值."
  • 使用 Setter 通常更好,因为您可以检查正在设置的值,而使用普通引用则不能保证调用者不会对数据做任何愚蠢的事情.
  • Passing by value in SetValue allows the compiler some optimizations that cannot be made with pass by const-reference, it's been explained in a article by Dave Abrahams, "Want Speed? Pass by Value."
  • Using a Setter is usually better, because you can check the value being set whereas with a plain reference you have no guarantee that the caller won't do anything stupid with the data.

对于吸气剂:

  • 通过复制返回似乎是一种浪费,因为大多数时候您不会修改返回的对象(对于设置映射),但是指针或引用确实意味着别名的对象将存活足够长的时间,如果您不能保证它那么重点是:按值返回.同时复制允许避免暴露内部细节,例如,如果您突然切换到 std::wstring 因为您需要一些 UTF-8 设置...
  • 如果你需要性能,那么你准备在这个部门做一些让步.然而,引用不允许您表示属性不存在(除非您有一些神奇的值),而指针则很容易(NULL 已经为您剪掉了).
  • Returning by copy seems a waste since most times you won't modify the object returned (for a settings map), however pointer or reference do mean that the object aliased will live long enough, if you can't guarantee it then the point is moot: return by value. Also copy allow to avoid exposing an internal detail, for example if you were suddenly to switch to std::wstring because you need some settings in UTF-8...
  • If you need performance, then you are ready to do some concessions in this department. However a reference does not allow you to signal the absence of the property (unless you have some magic value) while the pointer makes it easy (NULL is already cut out for you).

这篇关于C++ get 方法 - 按值或按引用返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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