为什么可以将非const引用参数绑定到临时对象? [英] Why can a non-const reference parameter be bound to a temporary object?

查看:515
本文介绍了为什么可以将非const引用参数绑定到临时对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char f1();
void f2(char&);

struct A {};

A    f3();
void f4(A&);

int main()
{
    f2(f1()); // error C2664. This is as expected.
    f4(f3()); // OK! Why???
}




错误C2664:'void f4 ;)':不能将参数1从'char'转换为
到'char&'

error C2664: 'void f4(char &)' : cannot convert argument 1 from 'char' to 'char &'

在C ++中,非const引用参数不能绑定到临时对象;在上面的代码中, f2(f1()); 会按预期触发错误。

I have been taught that in C++ a non-const reference parameter cannot be bound to a temporary object; and in the code above, f2(f1()); triggers an error as expected.

同样的规则不适用于代码行 f4(f3());

However, why does the same rule not apply to the code line f4(f3());?

即使我注释行 f2(f1()); ,那么包含 f4(f3()); code>将编译时不会出现任何错误或警告。

PS: My compiler is VC++ 2013. Even if I comment the line f2(f1());, then the code containing f4(f3()); will be compiled without any errors or warnings.

更新

MSDN 说:


在以前的Visual C ++版本中,非const引用可能是
绑定到临时对象。现在,临时对象只能绑定
到const引用。

In previous releases of Visual C++, non-const references could be bound to temporary objects. Now, temporary objects can only be bound to const references.

所以我认为这是一个VC ++的错误。我已提交错误报告至 VC ++小组

So I think it is a bug of VC++. I have submitted a bug report to VC++ team

推荐答案

如果使用 / Za选项禁用语言扩展,编译器拒绝这两个调用:

If you compile with the /Za option to disable language extensions, the compiler rejects both calls:

> cl /Za test.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 18.00.21005.1 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

test.cpp
test.cpp(11): error C2664: 'void f2(char &)' : cannot convert argument 1 from 'char' to 'char &'
test.cpp(12): error C2664: 'void f4(A &)' : cannot convert argument 1 from 'A' to 'A &'
        A non-const reference may only be bound to an lvalue

有几种(非常受限制的)编译器在启用语言扩展的情况下,将仍然允许非const常量引用绑定到右值表达式。我的理解是,这主要是为了避免破坏依赖这个扩展的几个巨大的遗留代码库。

There are several (very constrained) circumstances in which the compiler, with language extensions enabled, will still allow a non-const lvalue reference to bind to an rvalue expression. My understanding is that this is largely to avoid breaking several enormous legacy codebases that rely on this "extension."

(通常,不推荐使用/ Za原因,但主要是因为Windows SDK标头不能包含/ Za选项。)

(In general, use of /Za is not recommended for many reasons, but mostly because the Windows SDK headers cannot be #included with the /Za option.)

这篇关于为什么可以将非const引用参数绑定到临时对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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