簡體   English   中英

在具有智能指針的類上正確實現Copy構造函數和Equals運算符

[英]Proper Implementation of Copy Constructor and Equals Operator on a class with smart pointers

假設我要實現一個可復制的類,因此可以實現復制構造函數和賦值運算符。 但是,唯一和共享指針變量的正確實現和處理方式是什么? 請參閱以下人為設計的示例,其中包含兩種類型的指針:

頭文件

#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似乎是可行的方法。 一般而言。 我也許應該將其分解為一個單獨的問題。

共享指針呢? 我應該分配它還是使用make_shared函數?

tl; dr最有可能是您要尋找的任務。

這完全取決於所涉及類的語義。

  • 如果您希望對象共享shared_ptr的狀態,則需要分配或副本
  • 如果您希望每個對象保持其自己的狀態,則根據“其他”對象創建一個新的shared_ptr

如果不需要共享狀態,那么使用unique_ptr確實會更好

作為一般的“經驗法則”;

如果您的類型僅包含移動成員,則僅允許移動。 如果您的類型具有可復制成員,則允許復制。 在有意義的地方,遵循“值”類型的語義。 力爭“零規則”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM