Mail Archives: djgpp/1999/10/02/01:00:46
In a previous article, DavMac AT iname DOT com (Davin McCall) says:
>On Fri, 01 Oct 1999 19:45:14 GMT, wemccaug AT prairienet DOT org (Wendy E.
>McCaughrin) wrote:
>
>> The following example shows that 'gxx' will not invoke a copy-ctor
>> for temporaries, only for variables.
>
>Are you saying that's bad?
Well, It's not exactly kosher. Every C++ compiler I've used (dating
back at least as far as Borland 4.5) permitted this. Whether it's
"bad" depends upon the standard. (But read following.)
>
>The code you point out as not calling the copy-ctor instantiates a
>temporary instance of the class as a function parameter. The reason
>that the copy-ctor is not called is because no copy operation is
>performed - the temporary object is created directly on the stack
>before the function is called.
>
>The alternative, to construct the object and then copy it to the
>stack, would be less efficient.
This is a good point -- in fact, I was compiling with -O (but it
would be nice to be warned of such optimizations). BTW, if -O is
assuming that default (bit-wise) copy is always more efficient
than invoking the copy-ctor, doesn't that require some knowledge
of what the copy-ctor does? Suppose, e.g., that my copy-ctor could
avoid much of the bit-wise copy? Not relevant here, though.
>
>I am aware that this sort of thing can get confusing - I've been
>caught out by things like this myself.
>
>Davin.
>
>
>
>>
>>#include <iostream.h>
>>#include <string.h>
>>
>> class Overflow
>> { char mssg[80];
>> public:
>> Overflow( char* ccp ) { strcpy(mssg,ccp); }
>> Overflow( const Overflow& ovfl ) // must be 'const' !
>> { cerr << "copy ctor: "; strcpy(mssg,ovfl.mssg); }
>> void Report() { cerr << mssg; }
>> };
>>
>> void TstCpy( Overflow ); // call by value
>>
>> int main()
>> { Overflow of = " I am a variable\n";
>> TstCpy(of); // passing a variable: copy-ctor invoked
>> TstCpy(Overflow(" I am a temporary\n")); // passing temp: no copy-ctor
>> return 0;
>> }
>>
>>
>> void TstCpy(Overflow ovrflw)
>> { ovrflw.Report(); }
>>
>>
>> When compiled and run, the output is:
>>
>> copy ctor: I am a variable (indicating call of copy-ctor)
>> I am a temporary (defaults to bit-wise copy)
>
>__________________________________________________________
> *** davmac - sharkin'!! davmac AT iname DOT com ***
>my programming page: http://yoyo.cc.monash.edu.au/~davmac/
>
- Raw text -