Copy Semantics and Return Value Optimization

Unique Pointers and Copy Constructors

Why does the compiler generate an error when I try to define a copy constructor for a class containing a unique_ptr member?

Illustration representing computer hardware

When a class contains a unique_ptr member, the compiler-generated copy constructor is deleted because unique_ptr is not copyable. The purpose of unique_ptr is to ensure exclusive ownership of the pointed-to resource, so it cannot be copied.

To define a copy constructor for a class with a unique_ptr member, you need to manually implement the copying behavior. This typically involves creating a new unique_ptr in the destination object and copying the pointed-to resource.

Here's an example:

#include <memory>

class MyClass {
public:
  MyClass(const MyClass& other)
    : ptr{std::make_unique<int>(*other.ptr)} {}  

private:
  std::unique_ptr<int> ptr;
};

In the copy constructor, we create a new unique_ptr and initialize it with a copy of the value pointed to by other.ptr. This ensures that the destination object has its own independent copy of the resource.

By manually implementing the copy constructor this way, you can define the appropriate copying behavior for your class while still maintaining the exclusive ownership semantics of unique_ptr.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved