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

How to Handle Unique Pointers When Copying a Class?

Patricia Arquette
Release: 2024-12-15 16:00:24
Original
698 people have browsed it

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_)) {}
};
Copy after login

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_);
   }
};
Copy after login

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 after login
  • Copy Assignment:

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template