使用非内置类型的函数返回const值的用例是什么? [英] What are the use cases for having a function return by const value for non-builtin type?

查看:103
本文介绍了使用非内置类型的函数返回const值的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我读到,当从一个函数返回值,以限定非内置类型的返回类型const时,这是有意义的,例如:

Recently I have read that it makes sense when returning by value from a function to qualify the return type const for non-builtin types, e.g.:

const Result operation() {
    //..do something..
    return Result(..);
}



我一直在努力了解这个的好处,肯定是调用者选择决定返回的对象是否应该是const。

I am struggling to understand the benefits of this, once the object has been returned surely it's the callers choice to decide if the returned object should be const?

推荐答案

基本上,这里有一个轻微的语言问题。 / p>

Basically, there's a slight language problem here.

std::string func() {
    return "hai";
}

func().push_back('c'); // Perfectly valid, yet non-sensical

返回常数值是试图防止这种行为。然而,在现实中,它的方式比危害更好,因为现在,右值引用在这里,你只是要防止移动语义,这吸引,上述行为可能会被正确使用右值和左值 * this 重载。此外,你必须有点白痴做这反正。

Returning const rvalues is an attempt to prevent such behaviour. However, in reality, it does way more harm than good, because now that rvalue references are here, you're just going to prevent move semantics, which sucks, and the above behaviour will probably be prevented by the judicious use of rvalue and lvalue *this overloading. Plus, you'd have to be a bit of a moron to do this anyway.

这篇关于使用非内置类型的函数返回const值的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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