这是C++(GNU GCC编译器)中的指针数组的行为,我找不到解释,希望有人可以清除混淆。我创建了一个指针数组(arr_ptr),指针指向有效数据,然后创建另一个指针数组(arrcopy),我做了 - 我想 - 浅拷贝(arrcopy = arr_ptr) ,并且我得到了预期的数据...迄今为止非常好。指针数组无法解释的行为(与浅拷贝)C++
我不理解的部分是,在我删除arr_ptr后,不应该arrcopy仍然指向我的有效数据?为什么这不会发生? 谢谢。
int main()
{
int a = 1; int b=2; int c=3;
int* ap = &a; int* bp = &b; int* cp = &c;
// Array of pointers
int** arr_ptr = new int*[3];
arr_ptr[0] = ap;
arr_ptr[1] = bp;
arr_ptr[2] = cp;
//shallow copy
int** arrcopy = arr_ptr;
cout << "Values: " << *(arr_ptr[0]) << " " << *(arrcopy[0]) << endl;
cout << "Addresses: " << arr_ptr[0] << " " << arrcopy[0] << endl;
cout << endl;
a++;
cout << "After Incrementing a:" << endl;
cout << *(arr_ptr[0]) << " " << *(arrcopy[0]) << endl;
cout << arr_ptr[0] << " " << arrcopy[0] << endl;
cout << endl;
*(arr_ptr[0]) = 5;
cout << "After updating a value to 5:" << endl;
cout << *(arr_ptr[0]) << " " << *(arrcopy[0]) << endl;
cout << arr_ptr[0] << " " << arrcopy[0] << endl;
cout << endl;
//so far so good - works as expected
//deleting arr_ptr
delete[] arr_ptr;
// Why?: shouldn't arrcopy still be pointing to A
cout << "Values: " << *(arr_ptr[0]) << " " << *(arrcopy[0]) << endl; //The result I am expecting here is: unknown_value 5
cout << "Addresses: " << arr_ptr[0] << " " << arrcopy[0];
cout << endl;
return 0;
}
后arr_ptr浅拷贝到arrcopy(arrcopy = arr_ptr)
删除arr_ptr之后,不应该arrcopy仍然被指向的存储器位置,b,c数据值?!
'delete []'运算符还调用数组中所有元素的析构函数。我认为你的意思是一个简单的'删除'? –
'arrcopy = arr_ptr'表示您有2个指向*相同数组*的指针。通过一个指针删除数组,而对另一个无效。 – Galik
您没有制作数组的副本,只是将指针复制到数组。 – Galik