当有2个指针指向同一内存位置时,C ++删除指针 [英] C++ deleting a pointer when there are 2 pointers pointing to the same memory locations
问题描述
假设我有一个指针
int * l1 = new int [100 * 100]
int *l1 = new int[100*100];
int * l2 = l1;
int *l2 = l1;
l2都指向同一个整数序列。
我将一些值存储到它们中。
Now, l1 & l2 both point to the same sequence of integer. I store some values into them.
我说
delete [] l1;
delete [] l1;
是否删除l2?
如果我使用
打印l2的元素(int i = 1; i <= 10000; i ++){
for(int i=1; i<=10000; i++){
cout<<l2[i];
}
这些值是否打印完毕?
推荐答案
i2仍然指向同一个地方, 。尝试访问任何东西通过它是未定义的行为,这意味着您的值可能打印,或您的房子可能会起火。这不是由你决定的。
i2 still points to the same place, but that memory has now been freed. Trying to access anything through it is undefined behaviour, which means your values may be printed, or your house may catch on fire. It's not up to you.
为了保守,i1和i2都不被删除,但它们指向的内存是。它们仍然保持相同的值,但是那里的内存现在可以重用于其他事情。使用已传递给 delete
的指针是不安全的,因为内存中可能已经有其他内容。
To be pedantic, neither i1 nor i2 are deleted, but the memory they pointed to is. They still retain their same values, but the memory there can now be reused for other things. It's unsafe to use a pointer that has been passed to delete
because the memory might already have something else there.
这篇关于当有2个指针指向同一内存位置时,C ++删除指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!