访问器应该返回值还是常量引用? [英] Should accessors return values or constant references?

查看:29
本文介绍了访问器应该返回值还是常量引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 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.

这篇关于访问器应该返回值还是常量引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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