C++:创建指针的副本
C++: Create a copy of a pointer
我需要制作GameMaster* thisMaster
的副本,这样我就可以在保持"干净"副本的同时预处理操作。然而,按照我现在的做法,当我更改copy
时,它也会更改thisMaster
。
void Move::possibleMoves(GameMaster* thisMaster)
{
GameMaster* copy = new GameMaster(*thisMaster);
}
我该怎么解决这个问题?
edit:我创建了一个复制构造函数,但仍然有同样的问题。
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
};
这是浅拷贝与深拷贝的链接
players=gm.players;
只是在复制指针的集合。。你需要对新矢量中的玩家进行深度复制。
编辑
for( auto iter = gm.players.begin(); iter != gm.players.end(); ++iter)
{
players.push_back(new Players(*iter))
}
你还需要为玩家提供一个副本常量。
欢呼
相关文章:
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 指向基类的指针的 std::vector 的深层副本
- 如何让指针的深层副本将内部结构发送到内核?
- 带有随机指针的链表的深层副本
- 属于副本被推送到矢量的对象的指针会发生什么情况?
- 当我修改、更改和“删除”原始指针时,是否需要指针副本
- 我们如何在 C 中制作函数指针的深层副本
- 我如何创建一个双重指针的深层副本,涉及其他类(C )
- 在C++中制作此指针的本地副本
- 复制指针,在不更改原始指针的情况下更改副本指向的内容?
- 取消引用指针以创建数组的副本
- 移动语义是否只是一个浅层副本并将其他人的指针设置为 null?
- 如何使智能指针指向对象的副本
- 如果给出了该课程的指针,则深入应对以制作课程的副本
- C 指针深副本
- 对象或常量指针的副本
- C++:创建指针的副本
- 矢量和指针队列数据交换:深层和浅层副本
- 结构中的 CUDA 设备功能指针,没有静态指针或符号副本
- C++中的构造函数副本、列表、指针和模板