通过函数内部的指针删除

Deleting through pointers inside functions

考虑

void d(int* t) { //pointer passed by value
    delete t;
    std::cout << *t << '\n';
}

void d2(int*& t) { //pointer passed by reference
    delete t;
    std::cout << *t << '\n';
}

假设我们有:

int *y = new int{22};
d(y);
d2(y);

在这两种情况下,我预计:

std::cout << *t << '\n';

导致未定义的行为,因为我应该删除 t 的值。但我仍然可以成功取消引用它,就好像 "delete t;" 什么也没做一样。这是为什么?

"cause UB" / "But I can still dereference it successfully, as if "delete t;" did nothing. Why is that?"

"successfully" 可以编译,但不能编译 "don't have to worry about the UB" 中的 "succesfully"。为什么?因为编译器在编译期间不会尝试(或预期)对您的运行时程序状态进行建模:确保您的程序不会在运行时尝试具有未定义行为的行为是您的工作。

In the second case, my understanding is I passed it by reference, so still one pointer points to y

不...您没有任何指向 y 的指针...您有对 y 的引用。无论如何,int 不存在于 delete t 之后,相反:当您复制指针时 - 调用 d() 而不是 d2(),调用者的副本y 不受影响,成为指向 int 曾经所在位置的悬空指针(完全没用)。此外,如果调用 d(y);,则 d2(y);delete t; 语句中具有未定义的行为,而不仅仅是 *t.