引用限定符在gcc4.7.2和vc10中给出错误

ref qualifier gives error in gcc4.7.2 and vc10

本文关键字:vc10 错误 出错 gcc4 引用      更新时间:2023-10-16

考虑下面的最小示例:

#include<iostream>
struct A
{
    A(){std::cout<<"def"<<'n';}
    void foo()&{std::cout<<"called on lvalue"<<'n';}
};
int main()
{   
    A a;
    a.foo();
    A().foo();
    return 0;
}

给出expecting ';' at the end of declarationand expected un-qualified-id before '{'的错误。

我能知道我做错了什么吗?在实际代码中,我希望避免通过临时调用非静态成员函数。

在GCC 4.7.2和vc2010上试用。谢谢。

答案很简短:VC10和GCC 4.7.2不支持ref-qualifier。

但是,请注意您的foo()函数有一个左值 ref限定符,这意味着您不能在临时调用它。

如果您希望此表达式也可以编译:

A().foo();

那么您应该使用const&,或者为&&提供一个重载,就像这个实例一样。

可以使用Clang 3.2或GCC 4.8.1。