了解C ++中new和delete运算符背后的逻辑

辛戈

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

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

我认为这与第三个cout语句不符。我希望第三个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 ++ smartpointers,例如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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章