A
Alfred E Neuman
I've read that... AClass ac = AClass( "name", 23 );
is less efficient than... AClass ac( "name", 23 );
because the first has to create a temporary object which is then
assigned to ac.
However, I can't seem to prove this true. I've created a class
containing the following constructors and overloaded equal operator.
/* default constructor */ AClass();
/* main constructor */ AClass( const char *, int );
/* copy constructor */ AClass( const AClass & );
/* overloaded = operator */ AClass operator=( const AClass & );
I placed cout statements in each to show program execution flow.
AClass ac = AClass( "name", 23 ); executes my main constructor once
and a matching destructor call once. I never see any other
constructor or destructor calls.
However,
AClass ac;
ac = AClass( "name", 23 );
obviously calls two constructors; the default for object ac and then
the main constructor for the temporary object which is then assigned
to ac. Matching destructor calls are made as well. This makes sense
because of the two statement setup.
My confusion is that I see no difference between
AClass ac = AClass( "name", 23 ); and
AClass ac( "name", 23 );
What am I missing here? Was the information I read wrong? Is there
some kind of compiler optimization going on? I've tried this under
Microsoft Visual C++, Borland C++, and gcc on Linux, all with the same
results. I'm stumped.
is less efficient than... AClass ac( "name", 23 );
because the first has to create a temporary object which is then
assigned to ac.
However, I can't seem to prove this true. I've created a class
containing the following constructors and overloaded equal operator.
/* default constructor */ AClass();
/* main constructor */ AClass( const char *, int );
/* copy constructor */ AClass( const AClass & );
/* overloaded = operator */ AClass operator=( const AClass & );
I placed cout statements in each to show program execution flow.
AClass ac = AClass( "name", 23 ); executes my main constructor once
and a matching destructor call once. I never see any other
constructor or destructor calls.
However,
AClass ac;
ac = AClass( "name", 23 );
obviously calls two constructors; the default for object ac and then
the main constructor for the temporary object which is then assigned
to ac. Matching destructor calls are made as well. This makes sense
because of the two statement setup.
My confusion is that I see no difference between
AClass ac = AClass( "name", 23 ); and
AClass ac( "name", 23 );
What am I missing here? Was the information I read wrong? Is there
some kind of compiler optimization going on? I've tried this under
Microsoft Visual C++, Borland C++, and gcc on Linux, all with the same
results. I'm stumped.