为什么你不允许绑定一个非值引用的非const引用,但你允许调用非const成员函数 [英] Why are you not allowed to bind a rvalue reference to a non const reference but you are allowed to call non const member functions on one

查看:102
本文介绍了为什么你不允许绑定一个非值引用的非const引用,但你允许调用非const成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是大致相当的危险,但第二个2是不允许的语言,但第一个不是。

The following are roughly equivalent in terms of being dangerous but the second 2 are disallowed by the language yet the first one isn't.

#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> v;

    // allowed
    std::vector<int>().swap(v);

    // not allowed
    v.swap(std::vector<int>());

    // not allowed
    std::swap(std::vector<int>(), v);
}



我知道Visual Studio让所有这些通过作为一个编译器扩展,忽略了这个问题。

I know Visual Studio lets all these through as a compiler extension and I'm ignoring that for this question.

我不是在争论第一个被禁止 - 我实际上更喜欢第二个2被允许使代码更加优雅,通常当C ++让你做一些事情,这可能是危险的,但可以有益于它让它通过),但似乎奇怪的是,这里有一个差异。

I'm not actually arguing that the first one be disallowed - I'd actually prefer the second 2 be allowed (there are places where this makes code more elegant and normally when C++ lets you do some thing which may be dangerous but could be benefical it lets it through) but it seems weird that there is a difference here.

推荐答案

函数参数需要进行类型转换,这会创建一个临时的右值。这将产生混乱的结果,如果函数被传递一个非const引用该临时,当你期望它修改参数。这种潜在的混淆是不允许临时绑定到非常量引用的参考的理由。

Function arguments are subject to type conversions, which create a temporary rvalue. This would give confusing results if the function were passed a non-const reference to that temporary, when you expect it modify the argument. This potential confusion is a justification for not allowing temporaries to bind to non-const lvalue references.

对于其他引用类型没有相应的混淆; const 引用使对象保持不变,并且 rvalue 引用专门用于绑定到 rvalues 。也不会对成员函数产生问题,因为类型转换不适用于被调用的对象。

There is no corresponding confusion for other reference types; const references leave the object unmodified as expected, and rvalue references are specifically intended to bind to rvalues. Neither does the issue arise for member functions, since type conversions aren't applied to the object being called on.

这篇关于为什么你不允许绑定一个非值引用的非const引用,但你允许调用非const成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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