From: Goran on 11 May 2010 10:44 On May 11, 3:18 pm, Frank <j...(a)gmx.de> wrote: > This doesn't work: > > class C2 > { > ... > > C2(C2 &cRHS) That should be const, to assure that you don't change cRHS there (normally, you want to make a copy of an object, not to make a copy and change the original). Is it that C1 has this: C1::C1(const C1&rhs)? (if C1 has a default copt ctor, that's it's "invisible declaration"). there, rhs is const, and so C2 instance inside rhs is const. But C2 ctor wants a non-const reference, and you didn't give it that. Goran.
From: Frank on 11 May 2010 10:56 Goran wrote: > Is it that C1 has this: > > C1::C1(const C1&rhs)? > > (if C1 has a default copt ctor, that's it's "invisible declaration"). Many thanks - so this is the solution. C1 doesn't have an explicit copy constructor, so it uses the default which has a "const" argument, as you say.
From: Jerry Coffin on 11 May 2010 11:59
In article <4457d090-6b1e-41d4-932b- dcbf971d009f(a)l31g2000yqm.googlegroups.com>, jerk(a)gmx.de says... [ ... ] > Yes, thanks, I'll strip it down a bit because I found a > solution now but don't understand it - it works if I > make the parameter of the copy constructor of C2 > a "const": Yes -- if you have a type T, the parameter for its copy ctor should be 'T const &'. It's const for two reasons: first of all, a temporary can be bound to a reference to const T, but cannot be bound to a reference to (non- const) T. Second, a (normal) copy ctor has no business modifying what it's copying in any case. As far as what the "normal" refers to above, C++ 0x adds the concept of an 'rvalue reference'. The basic idea is that *if* you're copying a temporary object that's going to be destroyed after copying anyway, you can move the data from one object to another instead of making a whole new copy of the data, then destroying the old one. Especially for classes that contain large, dynamically allocated data (e.g. a string or vector) you can gain quite a lot of speed by "stealing" the data instead of copying it (typically doing a shallow copy instead of a deep copy). -- Later, Jerry. |