参数绑定c语言,c – 为什么非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???

}

error C2664: ‘void f4(char &)’ : cannot convert argument 1 from ‘char’

to ‘char &’

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

但是,为什么同样的规则不适用于代码行f4(f3());?

PS:我的编译器是VC 2013.即使我注释了行f2(f1());,那么代码包含f4(f3());将编译没有任何错误或警告.

更新:

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的一个bug.我已向VC++ team提交了错误报告

解决方法:

如果使用the /Za option编译来禁用语言扩展,则编译器会拒绝两个调用:

> 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左值引用绑定到rvalue表达式.我的理解是,这主要是为了避免破坏依赖于这种“扩展”的几个巨大遗留代码库.

(一般情况下,建议不要使用/ Za,原因很多,但主要是因为Windows SDK标头不能与/ Za选项一起使用.)

标签:object-lifetime,temporary-objects,c,const,reference

来源: https://codeday.me/bug/20190825/1718697.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值