Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: All
Mar 12, 1999

Prefer Initialization to Assignment of Objects

In general, assignment requires the creation and destruction of a temporary object, whereas initialization does not. This is true for not just for strings, but for every object type, so whenever you have the choice--prefer initialization to assignment. Consider this code snippet:
 
    string s1 = "Hello ",  s2 = "World", both;
    both = s1+s2;   // assignment rather than initialization; inefficient 
The compiler transforms the expression both = s1+s2; into:
 
    string temp (s1 + s2);  // store result in a temporary
    both = temp;   // assign 
    temp.Date::~Date();  // destroy temp
This snippet could have been written in a much more efficient way:
 
    string s1 = "Hello ",  s2 = "World";
    string both = s1+s2;  // initialization is more efficient than assignment
This time, the compiler transforms the expression both = s1+s2; into:
 
    string both (s1 + s2); 
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date