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.
这篇关于访问器应该返回值还是常量引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:访问器应该返回值还是常量引用?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
