简体   繁体   English

使用共享指针实现复制 c'tor?

[英]Implementing copy c'tor with shared pointer?

Since my last question caused a lot of confusion I'm completely going to rewrite it with more info.由于我的上一个问题引起了很多混乱,我将完全用更多信息重写它。

I have an abstract class Character which is being inherited by Soldier and Medic I wrote another class called Game to manage a game board similar to chess game, it has the following objects:我有一个抽象的 class Character ,它被Soldier和医生继承我写了另一个Medic名为Game来管理类似于国际象棋游戏的游戏板,它具有以下对象:

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

Note previously I had std::vector<Character*> board;注意之前我有std::vector<Character*> board; But was told by you that it's bad and I need to use smart pointers, while unique_ptr suits my code more but my professor wants me to use only shared_ptr .但是你告诉我这很糟糕,我需要使用智能指针,而unique_ptr更适合我的代码,但我的教授希望我只使用shared_ptr

The problem is that I don't know how to implement the copy c'tor.问题是我不知道如何实现复制 c'tor。 I wrote:我写:

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];
    }
}

But it seems wrong and too much (as I was told by you).但这似乎是错误的而且太多了(正如你所说的那样)。 Any help?有什么帮助吗?

Note: when I copy a game I don't want to have 2 games which share some pointers but spitted games so I could change one but not to affect the other.注意:当我复制一个游戏时,我不想让两个游戏共享一些指针但吐出游戏,这样我就可以改变一个但不影响另一个。

You need to make a copy of each Character object, for non abstract class without hierarchy this would be:您需要复制每个Character object,对于没有层次结构的非抽象 class,这将是:

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 ) );
}

assuming, that Character has proper copy ctor as well and it is not a pointer to base class which could be inherited.假设,该Character也具有正确的复制 ctor,并且它不是指向可以继承的基本 class 的指针。

In your case as it is abstract class and you point to derived ones you have to add pure virtual method clone() that returns std::shared_ptr<Character> to Character class and override it in every derived one:在您的情况下,因为它是抽象 class 并且您指向派生的,您必须添加纯虚拟方法clone() ,该方法将std::shared_ptr<Character>返回到Character class 并在每个派生的方法中覆盖它:

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

Then Game copy ctor would be:然后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() );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM