Eliminate Temporaries with op=()
In the previous discussion we have supplied the compiler with an existing object to work with so it will not invent a temporary one. That same idea can get recycled in other situations as well. Suppose that s3 does have a previous value and we are not in position to initialize s3 from scratch with:
string s3 = s1 + s2;
If we are looking at the case:
{ string s1,s2,s3; ... s3 = s1 + s2; ... }
we can still prevent the creation of a temporary. We can do that by using the string operator+=() and rewriting the code to use += instead of +, so
s3 = s1 + s2; // Temporary generated here
is rewritten as:
s3 = s1; // operator=(). No temporary. s3 += s2; // operator+=(). No temporary.
If string::operator+=() and ...
Get Efficient C++ Performance Programming Techniques now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.