首页 > 解决方案 > C ++:为什么可以在没有事先使用new的情况下对指向结构的指针使用delete?

问题描述

我对 C++ 比较陌生,并试图弄清楚如何正确删除结构。我知道 delete 运算符只能用于使用 new 运算符创建的指针。

但是,在结构的上下文中,特别是在二叉树中使用时,我现在经常看到类似的内容:

struct test_structure {
    int test_content;
}; 
test_structure *test_realization;
// Some code  
delete test_realization;

我不太明白为什么这样可以,即使没有使用 new 运算符来创建 test_realization。或者我在这里错过了什么?

标签: c++structbinary-treedelete-operator

解决方案


看起来您对“使用新运算符创建”一词感到困惑。所以当你写:

 test_structure *test_realization = new test_structure;

您不test_realization使用 operator new 创建自己,而是创建一个对象,返回并分配给它的指针test_realization。这样的对象可以稍后被 operator 销毁deletetest_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

虽然定义并始终初始化变量是个好主意,但这不是必需的。


推荐阅读