C++复制指针

C++ Copying Pointers

本文关键字:指针 复制 C++      更新时间:2023-10-16

嗨,我想知道如何将 2d Array C++指针的内容复制到另一个位置,并将另一个指针设置为它,以便在我对复制的指针进行更改时,原始数据不会发生任何变化?

基本上它是一个指向棋盘上棋子的数组指针。 所以它就像Piece * oldpointer = board[8][8]. 现在我想将此指针中的所有内容(包括 Pieces 头文件中的 getvalue(), getcolor() 等方法)复制到另一个位置,并设置指向它的指针,以便我可以在那里进行操作并测试它,而不必影响此原始数据?我在我不得不使用的地方读到allocate()但我不确定。请帮忙

在C++中,您可以按如下方式定义 2D 数组类型(您需要现代C++编译器):

#include <array>
typedef std::array<std::array<Piece, 8>, 8> board_t;

如果您的编译器不支持std::array则可以改用boost::array

#include <boost/array.hpp>
typedef boost::array<boost::array<Piece, 8>, 8> board_t;

现在您可以使用上面的类型。如我所见,您需要复制指针指向的对象:

board_t* oldpointer = new board_t;
// do some with oldpointer
// now make a copy of the instance of the object oldpointer points to
// using copy-constructor
board_t* newpointer = new board_t( *oldpointer );
// now newpointer points to the newly created independent copy
// do more
// clean up
delete oldpointer;
// do more with newpointer
// clean up
delete newpointer;

既然你使用的是C++,为什么不为你的 Piece 类定义一个复制构造函数呢?然后只是

Piece copied_piece(*board[8][8]);

如果你的类是 POD,你甚至应该能够使用默认的复制构造函数。

您可以通过在目标位置分配内存然后进行内存复制来复制

dest_pointer = (<<my type>>*) malloc(sizeof(<<my type>>);
memcpy(dest_pointer, src_pointer, sizeof(<<my type>>);

顺便说一句,这些方法永远不会被复制。 它们不属于对象。