理解c++中new和delete运算符背后的逻辑
understanding the logic behind the new and delete operators in c++
我试图理解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
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- typeid 运算符忽略 cv 限定符背后的理由是什么?
- 理解c++中new和delete运算符背后的逻辑