new在C++中的用法



超级愚蠢的问题,我想用c++创建一个二进制树,下面是我的代码

include <iostream>
using namespace std;
struct tree{
    tree * child_left = NULL;
    tree * child_right = NULL;
    int root;
    tree * parent = NULL;
};
int main(int argc, const char * argv[]) {
    tree *t1 = new tree;
    tree *t2 = new tree;
    tree *t3 = new tree;
    tree *t4 = new tree;
    tree *t5 = new tree;
    tree *t6 = new tree;
    tree *t7 = new tree;
    t4->root = 1;
    t5->root = 3;
    t6->root = 6;
    t7->root = 9;
    t2->root = 2;
    t2->child_left = t4;
    t2->child_right = t5;
    t3->root = 7;
    t3->child_left = t6;
    t3->child_right = t7;
    t1->root = 4;
    t1->child_left = t2;
    t1->child_right = t3;
    cout << t1->child_left->child_right->root;
    return 0;
}

这实际上可以工作,但如果我在声明这些节点时删除新的,xcode将出现类似(Thread1:EXC_BAD_ACCESS(代码=1,地址=0x10))的错误。

我想知道线程问题的原因,以及为什么在声明这些节点时需要使用new。

提前谢谢。

您正在声明指向树对象的指针。如果不使用new,就不会为指向的指针分配任何对象。

int main(int argc, const char * argv[]) {
tree t1, t2, t3, t4, t5, t6, t7;
  t4.root = 1;
  t5.root = 3;
  t6.root = 6;
  t7.root = 9;
  t2.root = 2;
  t2.child_left = &t4;
  t2.child_right = &t5;
  t3.root = 7;
  t3.child_left = &t6;
  t3.child_right = &t7;
  t1.root = 4;
  t1.child_left = &t2;
  t1.child_right = &t3;
  cout << t1.child_left->child_right->root;
  return 0;
}

这将负责在堆栈上创建对象,然后在作用域结束时自动销毁这些对象。

tree可能应该有一个接受参数的ctor,这样您就可以创建一个对象而不是一个数据包。

因为new关键字实际上创建了指针所指向的对象。如果没有new关键字,指针将被取消初始化,取消引用会导致未定义的行为。

此外,正确编写的代码必须始终delete所有使用new实例化的对象,以避免内存泄漏。在这个琐碎的例子中不需要,但最好尽早学习好习惯。

初始化指针时需要新语句,因为所有节点/树变量都是指针。在开发数据结构时,由于所有指针的性质(元素的动态数量、可以在数据结构上执行的操作几乎总是依赖于堆分配的值等),使用指针是很常见的。

我想我应该指出,当您使用关键字new时,实际上您在堆上创建了一个变量,并在堆栈上创建了指向该变量的指针。如果不使用单词new,则只会在堆栈上创建一个指针,而不是创建一个变量。

在c++中,无论何时在堆上分配某个东西,都必须记住在不再需要它时将其删除。与堆栈上的变量不同,这些变量不会自动删除,因为它们永远不会超出范围。你需要使用关键字delete,否则你会得到"内存泄漏"。

我建议您看一下这个快速教程,以澄清您的动态编程概念:http://www.cplusplus.com/doc/tutorial/dynamic/。

希望这能让你对正在发生的事情有一些了解!

最新更新