-1
const char* s1 = "John";
const char* s2 = new char[] {"Cena"};
// is s1 on stack?
// is s2 on heap?
...
// use s1 and s2
...

delete s1;
// do I need to delete s1?

delete[] s2?
// s2 definitely must be deleted right?

我在上面的评论中添加了我的问题。提前致谢。

4

1 回答 1

2

您可以删除使用运算符 new 创建的内容。

字符串文字具有静态存储持续时间。他们一直活着,直到程序结束。

在此代码段中

const char* s1 = "John";
const char* s2 = new char[] {"Cena"};

仅动态分配由字符串字面量初始化的数组"Cena"。因此,要删除它(释放分配的内存),您需要将运算符 delete [] 应用于指针s2

delete [] s2;
于 2022-03-03T14:55:55.593 回答