c++ - 如果我删除指向节点的指针数组,节点本身会被删除吗?

标签 c++ arrays pointers nodes delete-operator

假设我创建了一个指向节点的指针数组,每个节点包含一个汽车对象成员变量,以便按 mpg 的降序打印它们。一旦我按照 MPG 的降序对数组进行排序并打印出最终结果,我想删除我创建的指针数组。

删除最后的数组是否也会删除单链表中的节点?

cout << "\nCARS RANKED BY MPG\n-------------\n";

int capacity = count;                   //number of nodes in the list
Node **a = new Node*[capacity];            
int numOfElem = 0;

Node *currentCar = first;               //create a pointer to the first node in the list

while (numOfElem < count)
{
    a[numOfElem++] = currentCar;            //populate the array of pointers
    currentCar = currentCar->getLink();
}

//Do something....

delete[] a;                               //delete array of pointers
a = nullptr;        

最佳答案

不,你只是在释放 a 本身指向的内存。该内存的内容不会以任何方式处理。

如果你想自动“删除”对象,使用智能指针,或者更好的是 std::vector 对象(不是指向对象的指针)。

关于c++ - 如果我删除指向节点的指针数组,节点本身会被删除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49933382/

相关文章:

c++ - 二维对象数组 C++

php - 比较两个数组中具有匹配键的数值(使用阈值/容差)

javascript - 选择使用 javascript es5 更新或推送到数组

C 指针与指向指针的指针 - 正确用法是什么?

C奇怪的int数组指针

C++ STL 范围容器

c++ - 未定义的引用谷歌 Protocol Buffer 类

C++停止CAsyncSocket将单个大数据包拆分为多个小数据包

Java 扫描器输入数组

c++ - 如何将常量指针传递给类中的方法