Is this the standard behavior ?
Martin v. Loewis
martin@loewis.home.cs.tu-berlin.de
Sun Jan 2 16:41:00 GMT 2000
> I have a strange problem while porting a program from SUNWspro 4 C++
> compiler to GNU g++ 2.92.2
Thanks for your bug report. As this is really an issue with the
correct interpretation of the C++ standard, please ask in
comp.lang.c++.moderated or comp.std.c++ for information.
> I heared that in old C++ standard a copy constructor could be C::C(C&),
> but in modern C++ it should be C::C(const C &).
The implicit one is const C&; an explicit one can also be C&.
> In the assembler code I see the following. First constructor C::C(char
> *) is called to create an object in function f's local stack frame.
> Then, the operator char * is called for this object. Then, another C
> object is created (in the stack frame of the caller function). Then,
> destructor C::~C() is called to destroy the first C object.
The compiler is allowed to do this. It first constructs a temporary
object of type C from the const char* being returned, using C(char*):
C tmp("xxx");
It then needs to initialize the return value (in the caller's frame)
with that temporary. It seems that it could use two different
initializations:
C::C((C&)tmp);
and
C::C((char*)tmp);
However, the first conversion is not possible, because it requires
binding a temporary to a non-const reference, which is disallowed by
the standard. This was a recent change in C++, so older compilers
still think they can bind a temporary to the reference.
Since the other conversion is outlawed, the only remaining
initialization is the one with the user-defined conversion to char*.
> is the behaviour of g++ correct ?
Yes, see my explanation above. Also ask in comp.std.c++ if you are not
convinced.
> is this behaviour required by the modern C++ standard ?
The compiler is allowed to avoid the temporary, and to initialize the
return value directly. g++ currently does not perform this
optimization (at least not in this case).
> is it good to call implicitly the pair (operator char *,
> C(char *)) without even issuing a warning ? Is this
> standard ?
Yes, it is standard, and yes, it is good not to issue a warning. This
is caused by a temporary, and temporaries occur frequently.
> are there any g++ command-line swithes or other parameters
> that will make it to behave like Sun CC (that is, just
> to call constructor of the returned object)
Not that I know of.
> maybe, there are some workarounds ?
If you change the copy constructor to const C&, it will avoid the
temporaries.
Regards,
Martin
More information about the Gcc-bugs
mailing list