理解c++中new和delete运算符背后的逻辑

understanding the logic behind the new and delete operators in c++

本文关键字:背后 运算符 delete c++ new 理解      更新时间:2023-10-16

我试图理解c++中的delete运算符。

我可以理解使用指针和new运算符背后的逻辑,但我理解"delete运算符消除了一个动态变量,并将动态变量占用的内存返回给freestone。"p517,C++第9版的问题解决。

我认为这与第三个cout声明不一致。我原以为第三个声明会和第一个类似。

int main() {
    int  *p1;
    cout << "p1 address: " << &p1 << " and points to the address "<< p1 << " which has the value: " << *p1<< endl;
    p1 = new int;
    cout << "p1 address: " << &p1 << " and points to the address "<< p1 << " which has the value: " << *p1<< endl;
    delete p1;
    cout << "p1 address: " << &p1 << " and points to the address "<< p1 << " which has the value: " << *p1<< endl;
    cout << endl;
    return 0;
}

如果有任何解释,我将不胜感激:))

delete不必更改指针指向的内存。它实际所做的是特定于实现的。

delete需要做的是解构给定地址的任何对象,并将相关联的内存返回到分配池。某些调试器可能会在释放时覆盖变量的值,但对于琐碎的类型,不需要进行特殊的解构——内存可以按原样返回到池中。指针也没有改变:在delete p之后,我们将p称为一个悬挂指针,用于保存释放内存的地址。通过该指针进行的所有访问都是未定义的行为。

由于处理原始指针,尤其是悬空指针很容易出错,因此最好了解C++智能指针,例如unique_ptr:

std::unique_ptr<int> p;        // initialised to nullptr
p = std::make_unique<int>(13); // new int with value 13
p = std::make_unique<int>(37); // deleted previous int, assigned new int with value 37
// optional (when p goes out of scope its pointee is deleted automatically)
p.reset();                     // deleted the int and reset p to nullptr