c++ - 在具有智能指针的类上正确实现复制构造函数和等于运算符

标签 c++ pointers copy-constructor smart-pointers assignment-operator

假设我想实现一个可复制的类,那么我可以实现复制构造函数和赋值运算符。但是,唯一和共享指针变量的正确实现和处理是什么?请参阅此人为设计的示例,它具有两种类型的指针:

头文件

#include <memory>

using std::unique_ptr;
using std::shared_ptr;

class Copyable
{
private:
    unique_ptr<int> uniquePointer;
    shared_ptr<int> sharedPointer;

public:
    Copyable();
    Copyable(int value);
    Copyable(const Copyable& other);
    ~Copyable();

public:
    int GetUniqueValue() { return *uniquePointer; };
    int GetSharedValue() { return *sharedPointer; };
    Copyable& operator=(const Copyable& other);
};

CPP 文件

#include "stdafx.h"
#include "Copyable.h"

using namespace std;

Copyable::Copyable() : 
    uniquePointer(make_unique<int>()), sharedPointer(make_shared<int>())
{
}

Copyable::Copyable(int value) : 
    uniquePointer(make_unique<int>(value)), 
    sharedPointer(make_shared<int>(value))
{
}

Copyable::Copyable(const Copyable& other) : 
    uniquePointer(make_unique<int>(*other.uniquePointer)), 
    sharedPointer(make_shared<int>(*other.sharedPointer))
    // OR
    sharedPointer(other.sharedPointer)
{
}

Copyable::~Copyable()
{
}

Copyable& Copyable::operator=(const Copyable& other)
{
    if (&other != this)
    {
        uniquePointer.reset();
        uniquePointer = make_unique<int>(*other.uniquePointer);

        sharedPointer = make_shared<int>(*other.sharedPointer);
        // OR
        sharedPointer = other.sharedPointer;
    }

    return *this;
}

使用允许复制

Copyable copyable1(5);
int uniqueValue1 = copyable1.GetUniqueValue();
int sharedValue1 = copyable1.GetSharedValue();
Copyable copyable2 = copyable1;
int uniqueValue2 = copyable2.GetSharedValue();
int sharedValue2 = copyable2.GetSharedValue();

只有一种方法可以使用 make_unique 函数复制唯一指针,但是共享指针呢?我应该分配它还是使用 make_shared 函数?

更新 - 复制与移动

一个更广泛的说明我想弄清楚什么时候使用什么。如果我决定使用复制,为什么要使用 unique_ptr?看来 shared_ptr 是要走的路。同样,如果使用移动语义, unique_ptr 似乎是可行的方法。只是一般来说。我或许应该将其拆分为一个单独的问题。

最佳答案

What about the shared pointer? Should I assign it or use the make_shared function?

tl;dr 作业很可能是您要查找的内容。

这完全取决于所涉及类的语义;

  • 如果您希望对象共享 shared_ptr 的状态,则需要分配或复制
  • 如果您希望每个对象都保持其自身的状态,则基于“其他”对象创建一个新的shared_ptr

如果不需要共享状态,那么使用 unique_ptr

确实会更好

作为一般的“经验法则”;

If your type contains move only members, then only allow moving. If your type has copyable members, allow copying. Where it makes sense, follow the "value" type semantics. Strive for the "rule of zero"

关于c++ - 在具有智能指针的类上正确实现复制构造函数和等于运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24890215/

相关文章:

C++ 单向链表 - 双端队列 - InsertFront()

c++ - 创建不可复制对象的 vector

c# - c++ native 代码 DLL 使用抽象类到包装器中以在 C# 模块中使用

c++ - SFML 2.0 从 map 文件加载

C++ atof.如何检查输入错误?

c++ - 简单的逐帧视频解码器库

c++ - 如果表示为迭代器,则更改 C++ 类指针

c++ - 为什么指针没有隐式转换为 <type> const*const

c++ - 为什么拥有复制构​​造函数会导致此代码中断?

c++ - 如何在基类中使用复制构造函数?