Re: Can 'operator T const& () const' do any harm?
Thomas Mang wrote:
"Alf P. Steinbach" <alfps@start.no> schrieb im Newsbeitrag
news:4d66h4F190i9lU1@individual.net...
I gather that with C++0x we'll be able to write
class T { public: T(){} private: T( T const& ); };
void foo( T const& ) {}
int main() { foo( T() ); }
Currently this code is rejected by Visual C++ 7.1 (with
option /Za), Comeau Online version 4.3.3, and g++ 3.4.4.
However, this code:
class NoCopy
{
public: NoCopy() {}
private: NoCopy( NoCopy const& ); NoCopy& operator=( NoCopy
const& );
};
class T: public NoCopy {};
void foo( T const& ) {}
int main() { foo( T() ); }
is accepted by two of the three compilers mentioned above;
only g++ produces a compilation error (emits a diagnostic,
barfs, whatever).
Which makes me believe the minority is correct. The T bound to
the reference is an r-value. According to 8.5.3, second
bullet, the copy constructor for T nees to be available, even
if the r-value is directly bound to the reference.
It's a little bit more subtle than that. In class T, above,
there is an implicitly declared publically accessible copy
constructor, see ?12.8/4. You have to go down to ?12.8/7 to see
that 1) if the implicitly declared constructor is implicitly
defined, it is an error. And the normative text isn't really
that clear that the constructor will be implicitly defined in
this case -- all we have is a non-normative note saying that if
the constructor will be implicitly defined even if it is elided,
and a reference to 12.2, where it says clearly that the case in
question is assimilated to eliding the constructor. So while it
is clear that the intent is for this to be illegal, I don't
think it is 100% clear from just the normative text.
IOW, if that's correct, forget your conversion opertor, but
rewrite the expression calling foo instead.
The code with the conversion operator is correct. I wouldn't do
it, because I'd be afraid of it making other calls ambiguous,
but the example he posted is guaranteed to work according to the
standard.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]