Home >Backend Development >C++ >How to Handle Unique Pointers When Copying a Class?

How to Handle Unique Pointers When Copying a Class?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 16:00:24703browse

How to Handle Unique Pointers When Copying a Class?

Copying a Unique Pointer in a Class

Copying a class that contains a unique pointer as a member requires special consideration. A unique pointer cannot be shared, which necessitates either a deep copy of its contents or a conversion to a shared pointer.

Deep Copying

The deep copy approach creates a new unique pointer and initializes it with a copy of the original pointer's contents:

class A
{
   std::unique_ptr<int> up_;

public:
   A(int i) : up_(new int(i)) {}
   A(const A& a) : up_(new int(*a.up_)) {}
};

Here, A's copy constructor deep copies the int pointed to by the original unique pointer.

Conversion to Shared Pointer

Alternatively, you can convert the unique pointer to a shared pointer, which allows it to be shared among multiple objects:

class B
{
   std::unique_ptr<int> up_;

public:
   B(int i) : up_(new int(i)) {}
   B(const B& b)
   {
      up_ = std::make_shared(*b.up_);
   }
};

In this example, B's copy constructor converts the unique pointer to a shared pointer, enabling multiple copies of B to access the same underlying data.

Other Operators

To work seamlessly with containers, like std::vector, additional operators are typically required:

  • Move Constructor:

    B(B&& b)
    {
     up_ = std::move(b.up_);
    }
  • Copy Assignment:

    B& operator=(const B& b)
    {
     up_ = std::make_shared(*b.up_);
     return *this;
    }
  • Move Assignment:

    B& operator=(B&& b)
    {
     up_ = std::move(b.up_);
     return *this;
    }

These operators ensure that objects can be safely assigned and copied in various contexts.

The above is the detailed content of How to Handle Unique Pointers When Copying a Class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn