Subject: copty constructor vs assignment operator
Posted By: mitjit123 Post Date: 7/11/2006 12:41:34 AM
In chapter 8 ,regarding the concept on page 180 181
In case of
string s1,
s1 = myCell2.getString();

the copy constructor is called for creating the temporary obj
and then the assignment operator.

Then in case of

String s2 = myCell3.getString();

2 copy constructors should be called . One for creating temporary object and another for s2.
But copy constructor is getting called only once.
Why is this?




Reply By: klep Reply Date: 9/3/2006 2:10:11 AM
In the first example, s1 is already constructed (on the previous line) so the assignment operator will be used to assign the temporary result object to s1.

In the second example, the compiler recognizes that s2 is just being built, so it uses the copy constructor. The compiler is allowed to omit the temporary return object in this case as a performance enhancement -- there's really no need to call the copy constructor twice when the result value can be copied directly into s2.

Hope that helps!

Scott

----
Scott J. Kleper
Author, "Professional C++"
(Wrox, 2005)

Go to topic 44757

Return to index page 186
Return to index page 185
Return to index page 184
Return to index page 183
Return to index page 182
Return to index page 181
Return to index page 180
Return to index page 179
Return to index page 178
Return to index page 177