FAQ 33.07 What is the performance difference between Fred x(5)

FAQ 33.07 What is the performance difference between Fred x(5); and Fred y = 5; and Fred z = Fred(5);?

In practice, none. Therefore, use the one that looks most intuitive. This looks-most-intuitive notion depends on the situation there is no one-size-fits-all guideline as to which is best.

Each of the three declarations initializes an object of type Fred using the single- parameter constructor that takes an int (that is, Fred::Fred(int)). Even though the last two definitions use the equal sign, none of them use Fred's assignment operator. In practice, none of them creates extra temporaries either.

 #include <iostream> using namespace std; class Fred { public:   Fred(int) throw();   Fred(const Fred&) throw();   void operator= (const Fred&) throw(); }; Fred::Fred(int) throw()   { cout << "Fred ctor "; } Fred::Fred(const Fred&) throw()   { cout << "Fred copy "; } void Fred::operator= (const Fred&) throw()   { cout << "Fred assign "; } int main() {   cout << "1: ";  Fred x(5);         cout << '\n';   cout << "2: ";  Fred y = 5;        cout << '\n';   cout << "3: ";  Fred z = Fred(5);  cout << '\n'; } 

For most commercial-grade C++ compilers, the copy constructor is not called and the output of the program is as follows.

 1: Fred ctor 2: Fred ctor 3: Fred ctor 

Because they cause the same code to be generated, use the one that looks right. If class Fred is actually Fraction and 5 is the value of the numerator, the clearest is the second or third. If Fred is actually Array and 5 is the length of the Array, the clearest is the first or the third.

Note that if the user cannot access the copy constructor (for example, if the copy constructor is private:), only the first example is legal. Assuming that the compiler makes the appropriate optimization (a fairly safe assumption), the copy constructor isn't actually called; the user needs access to it as if it were called.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net