我试图理解c ++中的删除操作符。
我可以理解使用指针和新运算符背后的逻辑,但我理解" 删除运算符会消除动态变量并返回动态变量占用到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;
}
我将不胜感激任何解释:))
答案 0 :(得分:1)
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