为什么 C++ 堆中的垃圾位置没有设计为可以自行重新分配?

Why is the garbage location in the heap in C++ not designed as can be reallocated itself?

我正在学习堆,我被告知如果我们必须将指针重新分配到一个新地址,我们必须删除指针指向的堆地址中的内容,否则该内容将成为垃圾并且可能会导致内存泄漏。喜欢:

int* x = new int(10);
//delete x
x = new int(12) //without deleting x, the address that holds value 10 becomes garbage.

因此我在想,虽然该语言没有 GC,但为什么该语言没有通过使非指向堆地址能够自行重新分配来更新?那么当地址重新分配时,垃圾内容可以用新的有效值替换,因此垃圾收集器也可以省略?

谢谢,如有错误请指出:)

如果没有某种引用跟踪,就无法实现这一点。

考虑对您的代码进行以下修改:

int* y;
// somewhere else:
int* x = new int(10);
y = x;
x = new int(12);  // oops: y has now unexpected become invalid

也就是说,x指向的内存位置已经被复制到另一个指针,y,然后x被重新分配。如果x的重新赋值自动破坏了它之前指向的数据,那么y也会失效。

那将是不受欢迎的行为,因此您需要某种引用跟踪系统来确保 x 指向的数据未被删除 除非 x 是对该数据的唯一引用。

现在您刚刚重新发明了 (a type of) garbage collection

事实上,尽管如此,C++ 确实有一种优雅的方式来实现这种类型的引用跟踪:通过 RAII, or what I prefer to refer to as "scope-bound resource management". Specifically for pointers to memory locations, you would use a smart pointer class 根据需要自动管理内存的分配和释放。