C++:创建指针的拷贝

标签 c++ pointers copy

我需要制作一份 GameMaster* thisMaster 的拷贝,这样我就可以在执行操作的同时仍然保持“干净”的拷贝。然而,我现在的做法是,当我对 copy 进行更改时,它也会更改 thisMaster

void Move::possibleMoves(GameMaster* thisMaster)
{
     GameMaster* copy = new GameMaster(*thisMaster);
}

我该如何解决这个问题?

编辑:我创建了一个复制构造函数,但仍然有同样的问题。

GameMaster::GameMaster(const GameMaster& gm)
{
    for(int i=0;i<GAMETILES;i++)
    {
        gameTiles[i]=gm.gameTiles[i];
    }
    players=gm.players;
    vertLines=gm.vertLines;
    horLines=gm.horLines;
    turn = gm.turn;
    masterBoard=gm.masterBoard;
    lastLegal=gm.lastLegal;
    lastScore=gm.lastScore;
}

这是 GameMaster 的完整类定义:

Class GameMaster
{
public:
    GameMaster(void);
    GameMaster(const GameMaster& gm);
    ~GameMaster(void);
    //functions

private:
    std::vector <Player*> players;
    std::vector <Line> vertLines;
    std::vector <Line> horLines;
    Tile gameTiles [GAMETILES];
    std::vector <std::string>colors;
    std::vector <std::string>shapes;
    int turn;
    Board masterBoard;
    bool lastLegal;
    int lastScore;
};

对于复制构造函数,我仍然遇到 Board 更改值的问题。它是否也需要复制构造函数?

最佳答案

Class GameMaster
{
public:
    GameMaster(void);
    GameMaster(const GameMaster& gm);
    ~GameMaster(void);
    //functions

private:
    std::vector <Player*> players; // You should make a deep copy because of pointers
    std::vector <Line> vertLines; // Shallow copy is OK if Line doesn't have pointers in it
    std::vector <Line> horLines; // see above
    Tile gameTiles [GAMETILES]; // One by one assignment is OK
    std::vector <std::string>colors; // Shallow copy is OK
    std::vector <std::string>shapes; // Shallow copy is OK
    int turn; // assignment is OK
    Board masterBoard; // same questions for GameMaster still exists for copying this
    bool lastLegal; // assignment is OK
    int lastScore; // assignment is OK
};

这是 Shallow vs Deep copy 的链接

关于C++:创建指针的拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12103749/

相关文章:

c++ - 函数指针和 C++ 模板

javascript - 将值从表行复制到剪贴板(PHP、SQL 和 JS)

copy - Gnome shell 扩展,将文本复制到剪贴板

java - 如何修复返回额外的零

c - 为数组动态分配内存时(在 C 中),(int *) 强制转换的作用是什么?

c++ - clang 交错源代码和程序集

c++ - C++设计:基类构造函数和自定义字符串类的is-a或has-a关系

C++ 在枚举中使用 ASCII 而不是字母

c++ - 让子对象引用其父对象而不是指针是不好的做法吗?

c++ - 用静态库构建共享库