Redundant Construction

Along the lines of simple but costly coding mistakes, here's another example of pure overhead. It is the double construction of a contained object [Mey97 item 12], [Lip91].

Class Person contains an object of class string:

class Person {
public:
    Person (const char *s) { name = s; }// Version 0
    ...

private:
    string name;
};

Consider the following implementation of the Person default constructor:

Person (const char *s) { name = s; }

The Person object must be initialized before the body of the Person constructor is executed. The contained string object does not appear in the Person::Person(char*) initialization list (in this case there was none). Hence, the compiler must insert a call to invoke the string default constructor, ...

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.