devxlogo

Prefer Initialization to Assignment of Objects

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); 
See also  How IoT Tech Will Transform Logistics
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist