Should accessors return values or constant references?(访问器应该返回值还是常量引用?)
问题描述
假设我有一个 Foo
类和一个 std::string
成员 str
.get_str
应该返回什么?
Suppose I have a class Foo
with a std::string
member str
. What should get_str
return?
std::string Foo::get_str() const
{
return str;
}
或
const std::string& Foo::get_str() const
{
return str;
}
在 C++ 中什么是更惯用的?
What is more idiomatic in C++?
推荐答案
简短的回答是:这取决于:-)
The short answer is: it depends :-)
从性能的角度来看,返回引用(通常)更好:您保存了一个新的 std::string
对象的创建.(在这种情况下,创建成本足够高,并且对象的大小足够大,以证明做出这个选择至少值得考虑——但情况并非总是如此.对于较小的或内置的——在类型上性能差异可能可以忽略不计,或者按值返回甚至可能更便宜).
From the performance point of view returning a reference is (usually) better: you save the creation of a new std::string
object. (In this case, the creation is costly enough and the size of the object is high enough to justify make this choice at least worth considering - but this is not always the case. With a smaller or built-in type the performance difference may be negligible, or returning by value may even be cheaper).
从安全的角度来看,返回原始值的副本可能会更好,因为常量可以被恶意客户端抛弃.如果该方法是公共 API 的一部分,则尤其要考虑这一点,即您(或团队)无法完全控制(错误)使用返回值的方式.
From the security point of view returning a copy of the original value may be better, as constness can be cast away by malicious clients. This is especially to be taken into consideration if the method is part of a public API, i.e. you(r team) have no full control over how the returned value is (mis)used.
这篇关于访问器应该返回值还是常量引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:访问器应该返回值还是常量引用?


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07