【问题标题】:Implementing copy c'tor with shared pointer?使用共享指针实现复制 c'tor?
【发布时间】:2020-10-15 02:53:03
【问题描述】:

由于我的上一个问题引起了很多混乱,我将用更多信息完全重写它。

我有一个 abstractCharacterSoldierMedic 继承 我写了另一个类Game来管理一个类似象棋游戏的棋盘,它有以下对象:

    mtm::Dimensions dimensions;
    std::vector<std::shared_ptr<Character>> board;

注意我之前有std::vector&lt;Character*&gt; board;,但被你告知它很糟糕,我需要使用智能指针,而unique_ptr 更适合我的代码,但我的教授希望我只使用shared_ptr

问题是我不知道如何实现复制 c'tor。我写道:

Game::Game(const Game &other): dimensions(other.dimensions), board(dimensions.getRow()*dimensions.getCol()) {
    int board_size= dimensions.getRow()*dimensions.getCol();
    for (int i=0;i<board_size;++i)
    {
        this->board[i]=other.board[i];
    }
}

但这似乎是错误的,而且太过分了(正如你所说的那样)。有什么帮助吗?

注意:当我复制一个游戏时,我不想让两个游戏共享一些指针但吐出游戏,这样我就可以更改一个但不影响另一个。

【问题讨论】:

  • other.board有大小,为什么还要计算大小?
  • @Slava 你指的是哪一行?
  • 我指的是int board_size=...,你得到的值与other.board.size()完全相同
  • 没有名为 size() @Slava 的函数

标签: c++ class methods shared-ptr smart-pointers


【解决方案1】:

您需要复制每个 Character 对象,对于没有层次结构的非抽象类,这将是:

Game::Game(const Game &other): dimensions(other.dimensions) 
{
    board.reserve( other.board.size() );
    for( const auto &pch : other.board )
       board.push_back( std::make_shared( *pch ) );
}

假设,Character 也有正确的复制 ctor,它不是指向可以被继承的基类的指针。

在您的情况下,因为它是抽象类并且您指向派生类,所以您必须添加纯虚方法 clone(),该方法将 std::shared_ptr&lt;Character&gt; 返回到 Character 类并在每个派生类中覆盖它:

class Character ... {
public:
    virtual std::shared_ptr<Character> clone() const = 0;
    ...
};

那么 Game 复制 ctor 将是:

Game::Game(const Game &other): dimensions(other.dimensions) 
{
    board.reserve( other.board.size() );
    for( const auto &pch : other.board )
       board.push_back( pch->clone() );
}

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    相关资源
    最近更新 更多