Copy constructor with non const rhs arg
paul moore
paulmoore100@hotmail.com
Wed May 12 18:43:00 GMT 2004
Thanks to everybody for their input.
Using mutable worked a treat (first time I have used it in anger - you live
and learn)
-----Original Message-----
From: llewelly@xmission.xmission.com [mailto:llewelly@xmission.xmission.com]
On Behalf Of llewelly@xmission.com
Sent: Wednesday, May 12, 2004 11:09 AM
To: paul moore
Cc: gcc-help@gcc.gnu.org
Subject: Re: Copy constructor with non const rhs arg
"paul moore" <paulmoore100@hotmail.com> writes:
> This code does not compile on gcc (3.2.2 on rh9 - 3.3 on suse 9)
>
> class test
> {
> public:
> int x;
> test(test &rhs)
> {
> x = rhx.x;
> }
> };
>
> test foo();
> int main(int argc, char* argv[])
> {
> test dd = foo();
C++ does not allow binding a temporary to a reference to non-const.
> return 0;
> }
>
> The test dd line gets hit saying there is no match for
> test::test(test), the candidates are test::test(test&) If I change the
> copy constructor to 'test(const test&)' it compiles fine.
>
> What am I trying to do? In real life the class contains an auto_ptr -
> since the auto_ptr copy constructor updates the rhs you cannot pass it
> in with const. (Note the auto_ptr copy constructor itself is declared
> with a non const rhs - and code using it compiles fine - this is
> really
> puzzling)
auto_ptr uses a truly hideous trick involving a sort of proxy class
called auto_ptr_ref. You are probably better off not tryiing to
emulate it. If you *need* to emulate it, you'll have to look at
the sources; I can't explain it.
>
> Also if I change foo to 'test &foo()' it compiles fine (but of course
> this is totally different semantics) Note also that MSFT vs 2003
> compiles this code quite happily.
M$ supports binding a temporary to a reference to non-const as an extension.
More information about the Gcc-help
mailing list