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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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