将指针分配给另一个指针时会发生什么情况?

What is happening when you assign a pointer to another pointer?

本文关键字:指针 什么情况 分配 另一个      更新时间:2023-10-16

代码:

int x = 2;
int* pointerone = &x;
int* pointertwo = pointerone;

因此,pointerone的地址被分配给pointertwo,但是是被调用的复制构造函数,并且保存该地址的对象被复制到另一个指针的地址对象中,就像执行浅拷贝的其他类型上的所有默认复制构造函数一样。如果如我所料,指针的复制构造函数是什么样子的?

这里不涉及构造函数。实际上,此代码是纯 C 代码。

int x = 2;
// pointerone points to the memory address of x
int* pointerone = &x;
// pointertwo points to the same address than pointerone,
// therefore it points also to the memory address of x
int* pointertwo = pointerone;

就这样。

即使在C++中,指针也没有构造函数,就像int类型没有构造函数一样。

为了对称性,你可以假装指针的复制构造函数正在被调用(这将涉及单个数字"内存地址"的复制(。

实际上,指针是内置类型的,本身没有构造函数。编译器具有内置逻辑,告诉它使程序做什么。

当你用另一个指针的值初始化一个指针时,你只是在为相同的内存地址创建另一个变量,正如@Michael刚才所说。

但要小心这样做。如果删除其中一个指针,并在程序的另一个点取消引用另一个指针,它将引发异常,如果处理不当,程序将崩溃。

以这个为例:

int *ptr1 { new int(15) };
int *ptr2 { ptr1 }; // ptr2 points to same memory address as ptr1
// ... Some cool code goes here
delete ptr1; // Free the memory of ptr1
cout << *ptr2;
// Raises an exception because the address
// has been removed from the effective
// memory of the program.