default parameter value for a reference from a constructor
Ian Lance Taylor
iant@google.com
Wed Oct 6 00:52:00 GMT 2010
<gongweigang@gmail.com> writes:
> I have following code:
>
> class A { };
>
> class B
> {
> public:
> void foo( A& ra = A() ) { }
> };
>
> int main() {
> return 0;
> }
>
> If I compile with g++, it has following error message: invalid type
> A' for default argument to 'A&'.
>
> But when I compile it using SunStudio compiler, it works.
>
> I suspect the error is due to set the default value for reference "ra"
> with a constructor.
>
> Can anyone explain whether the above code is valid in C++ standard ?
> If not, how to make it work by g++ ?
The C++0x draft [dcl.fct.default] says that default arguments use
copy-initialization semantics. Then [dcl.init.ref] says that if you
initialize a reference with something which is not an lvalue, then the
reference must be const. So I think this is invalid C++. I'd be happy
to hear a correction here.
Ian
More information about the Gcc-help
mailing list