访问器应该返回值还是常量引用?
假设我有一个 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.
相关文章