O'Reilly logo

Efficient C++ Performance Programming Techniques by David Mayhew, Dov Bulka

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required