复制指针,更改副本指向的内容而不更改原始内容?

Copying a pointer, change what the copy is pointing to without changing original?

是否可以复制一个指针,然后在不改变原始指针指向的情况下改变它指向的值?

例如,假设我有以下内容:

int *i;
auto j = i;

*j = new_val;

这将更改存储在 i 指向的地址处的值,因为 ij 都指向相同的内存地址,这是我不想要的。

由于这个示例非常简单,我可以简单地创建一个新的 int *j 而无需复制 i。但是在更复杂的情况下,比如链表,我不想重新创建链表。

所以我想我的问题归结为是否可以复制指针,并让副本指向不同的地址但保持原始指针的结构完整性?

首先澄清一下。指针是一个独立的变量,它保存了一个内存地址。仅此而已。指针的类型意味着您,程序员,告诉编译器存储在该地址的内容,以便您可以检索存储在该地址的值——这称为取消引用。

现在考虑到这一点,您应该能够自己计算出您想做什么,但让我们逐步完成该过程,我们将使用智能指针,因为它们可以帮助我们管理内存:

std::unique_ptr<int> i = std::make_unique<int>(10); 
//Here we created a variable on the heap and gave it a value 10,
//the address of it is stored in **i**

std::unique_ptr<int> j = std::make_unique<int>(*i);
//Here we created a variable on the heap nad gave it a value
//stored at the address in **i**. Notice the dereferencing
//that means we want to copy the value pointed to,
//not the pointer itself.

现在没有智能指针,如果这对你更有意义的话:

int *i = new int(10);
int *j = new int(*i);
delete i;
delete j;

这做同样的事情,但你需要自己管理内存,例如当抛出异常时它会泄漏。

现在这将适用于示例中的 int 之类的所有类型或定义了复制构造函数的所有类型。编译器通常会自动为您的类型生成一个,除非由于某种原因它不能这样做,在这种情况下您必须自己提供它:

详情请看这里:Copy Constructors

编辑:一些非常好的指针解释,包括演示如何做你想做的事:C++ Pointers by TheCherno