liveBook · Manning

Copy constructor

As explained in 100 C++ Mistakes and How to Avoid Them

A copy constructor is a C++ special member function that initializes an object from another object of the same class by copying its state.

A copy constructor initializes a new C++ object from another object of the same class. It differs from copy assignment, which replaces the state of an already initialized object. Both must preserve the class invariant, but assignment must also account for resources the target already owns. section 8.5 section 8.0

A file reader with an owned array

An InputReader owns a dynamically allocated array of filenames. A default member-wise copy copies the pointer, not the array. Two readers then refer to the same storage: changes can affect both, and destruction can attempt to delete the same array twice. A copy constructor can instead allocate a new array and copy the filenames into it. section 8.5

Listing 8.9 A properly written copy constructor and assignment operator
class InputReader {
private:
    std::string* filenames;
    int count;
public:
    InputReader() : filenames(new std::string[5]), count(0) {}
    ~InputReader() { delete[] filenames; }
    InputReader(const InputReader& r) : filenames(new std::string[5]), 
            count(r.count) {                                #1
        for (int i = 0; i < r.count; ++i)
            filenames[i] = r.filenames[i];
    }
    InputReader& operator=(const InputReader& r) {          #2
        for (int i = 0; i < r.count; ++i)
            filenames[i] = r.filenames[i];
        count = r.count;
        return *this;    }
    void addFileName(const std::string& n) {
        if (count == 5)
            throw std::runtime_error("too many files specified");
        filenames[count++] = n;
    }
    int getCount() const { return count; }
    const std::string& operator[](int index) {
        return filenames[index];
    }
};
 
int main() {
    InputReader ir1;
    ir1.addFileName("statistics.txt");
    InputReader ir2(ir1);                                 #3
    ir2.addFileName("numbers.txt");
    InputReader ir3 = ir2;                                #4
    ir3.addFileName("categories.txt");
    ir1.addFileName("questions.txt");
 
    for (int i = 0; i < ir1.getCount(); ++i)
        std::cout << ir1[i] << '\n';
    for (int i = 0; i < ir2.getCount(); ++i)
        std::cout << ir2[i] << '\n';
    for (int i = 0; i < ir3.getCount(); ++i)
        std::cout << ir3[i] << '\n';
    return 0;
}

Compare the copy constructor, which allocates storage for a new reader, with assignment, which copies into an existing reader's array. section 8.5

Check ownership before writing a copy constructor. A pointer may refer to shared data or to a resource each object must own separately. For the latter, copying the pointer alone can break the class invariant. Coordinate copy construction with copy assignment and destruction when the class manages resources directly. section 7.6 section 8.5

Listing 7.9 Adding uniqueness preserving, move construction, and assignment
class TextSection {
    // assume a clever implementation
};
 
class Page {
private:
    TextSection* headers;
    std::unique_ptr<TextSection> body;
public:
    Page(TextSection* h) : headers(h),
body(std::make_unique<TextSection>()) {}
    Page(const Page& o) : headers(o.headers),
body(std::make_unique<TextSection>(*o.body)) {}
    Page& operator=(const Page& o) {
        headers = o.headers;
        body = std::make_unique<TextSection>(*o.body);
        return *this;
    }
    Page(Page&&) = default;                                #1
    Page &operator=(Page&&) = default;                     #2
};
 
int main() {
    Page p1(new TextSection());
    Page p2 = p1;
    return 0;
}

The Page copy constructor keeps the shared header pointer but creates a separate body managed by std::unique_ptr; move operations are defaulted. section 7.6

A handwritten copy constructor is not always needed. Compiler-provided member-wise copying can be appropriate for value-based members such as std::vector, provided their copy behavior matches the class's intent. Use =default for a suitable compiler-generated member and =delete to make an unwanted operation explicit; check which special members are generated when others are declared. section 2.4 section 8.5

Watch for copies outside explicit object initialization:

  • A range-based loop with a class-type variable by value copies each element. Use a const reference for read-only access, or a non-const reference when modifying elements. section 2.6
  • Returning a local object by value avoids a dangling pointer or reference. A copy may incur overhead, but return value optimization can eliminate some of it. section 11.4

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Contrasts member-wise and resource-preserving copies, with implementations and comparison to copy assignment.
Examples
Compares a file reader's copied array with a page's uniquely owned body and a vector-backed container.
What you can do after
Apply copy construction when defining resource-owning classes, and identify unnecessary copies in loops.
How it connects
Connects copy constructors to copy assignment, destructors, class invariants, move operations, and range-based loops.

Also explained in

Compare how 2 books explain copy constructor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.