c++ - C ++:为什么可以在没有事先使用new的情况下对指向结构的指针使用delete?
问题描述
我对 C++ 比较陌生,并试图弄清楚如何正确删除结构。我知道 delete 运算符只能用于使用 new 运算符创建的指针。
但是,在结构的上下文中,特别是在二叉树中使用时,我现在经常看到类似的内容:
struct test_structure {
int test_content;
};
test_structure *test_realization;
// Some code
delete test_realization;
我不太明白为什么这样可以,即使没有使用 new 运算符来创建 test_realization。或者我在这里错过了什么?
解决方案
看起来您对“使用新运算符创建”一词感到困惑。所以当你写:
test_structure *test_realization = new test_structure;
您不test_realization
使用 operator new 创建自己,而是创建一个对象,返回并分配给它的指针test_realization
。这样的对象可以稍后被 operator 销毁delete
。test_realization
是一个具有指向类型指针的变量,test_structure
并且与任何其他变量一样,它可以保存不同的值,可以在定义时进行初始化,也可以不进行初始化。因此,当有人说指针“使用 new 运算符创建”时,他的意思是值,您将其分配给test_realization
非变量test_realization
本身。
test_structure *test_realization;
...
test_realization = new test_structure; // now test_realization points to object that created by new
test_realization->test_content = 123; // we can use that object
...
delete test_realization; // now object, which was created by new destroyed and memory released
虽然定义并始终初始化变量是个好主意,但这不是必需的。
推荐阅读
- c# - EF Code-First 方法 - 无法创建 SQL Server 数据库
- javascript - 为什么 Math.sign([]) = 0,Math.sign([20]) = 1,Math.sign([20, 30, 40]) = NaN?
- php - 在数组值中指定路径包括?
- php - PrestaShop 1.7 配置,appParameters.php 的权限被拒绝
- c++ - 无法理解二进制文件读取
- function - 从 VS Code 部署 Azure 函数
- build - Bazel 增量构建结果
- c# - 是否可以为另一个 ui 元素调用我的 listview 元素?
- angular - 如何以角度轻松地从用户那里选择日期和时间?
- django - 如何在 Django 中查询两个以上的表?