Here is an excerpt from Art. 56 books "C ++ Gotchas":
It is not uncommon to see a simple initialization of an object Y written in any of three different ways, as if they were equivalent.
Y a( 1066 ); Y b = Y(1066); Y c = 1066;
In fact, all three of these initializations are probably in the same object code, but they are not equivalent. The initialization of a is known as direct initialization, and this is exactly what could be expected. Initialization is done through a direct call to Y :: Y (int).
The initialization of functions b and c is more complicated. In fact, they are also complicated. This is a copy of the initialization. In the case of initialization b, we request the creation of an anonymous temporary type Y, initialized with the value 1066. Then we use this anonymous temporary value as a parameter for the copy constructor for class Y to initialize b. Finally, we call the destructor for anonymous temporary.
To test this, I made a simple class with a data member (the program is attached at the end), and the results were amazing. It seems that for case c, the object was constructed by the copy constructor, rather than proposed in the book.
Does anyone know if the locale has changed or is it just a compiler optimization function? I used Visual Studio 2008.
Code example:
#include <iostream> class Widget { std::string name; public: // Constructor Widget(std::string n) { name=n; std::cout << "Constructing Widget " << this->name << std::endl; } // Copy constructor Widget (const Widget& rhs) { std::cout << "Copy constructing Widget from " << rhs.name << std::endl; } // Assignment operator Widget& operator=(const Widget& rhs) { std::cout << "Assigning Widget from " << rhs.name << " to " << this->name << std::endl; return *this; } }; int main(void) { // construct Widget a("a"); // copy construct Widget b(a); // construct and assign Widget c("c"); c = a; // copy construct! Widget d = a; // construct! Widget e = "e"; // construct and assign Widget f = Widget("f"); return 0; }
Output:
Constructing Widget a Copy constructing Widget from a Constructing Widget c Assigning Widget from a to c Copy constructing Widget from a Constructing Widget e Constructing Widget f Copy constructing Widget from f
What surprised me most was the results of building d and e. To be precise, I expected an empty object to be created, and then an object to be created and assigned to an empty object. In practice, objects were created by the copy constructor.
c ++ assignment-operator constructor copy-constructor
Andy
source share