new[]必须与delete[]配对使用,因为new[]分配数组时会存储元素数量等元数据,delete[]据此调用每个对象的析构函数并释放全部内存;若误用delete,仅首个对象可能被析构,导致内存泄漏或程序崩溃;推荐使用std::unique_ptr<T[]>等智能指针自动管理数组内存,避免手动配对错误。
![c++内存管理基础中new[]和delete[]使用规范](https://img.php.cn/upload/article/000/969/633/175746816391971.png)
C++中,分配数组内存用
new[]
delete[]
new
delete
[]
[]
[]
[]
深入一点讲,
new[]
delete[]
new[]
delete[]
delete[]
new
new[]
new[]
delete[]
这问题其实挺核心的,理解了它,很多内存管理的坑就能避开。简单来说,
new[]
delete[]
std::string
string
delete[]
string
delete
delete[]
string
delete
new[]
new[]
new
new[]
嗯,这是一个非常常见的错误,后果也相当严重。当你用
new
new[]
int
char
double
std::string
new
std::string
new
new[]
delete
new[]
立即学习“C++免费学习笔记(深入)”;
new[]
delete[]
避免这种低级错误,最有效的方法就是少用甚至不用裸指针和手动内存管理。C++11及以后版本引入的智能指针(Smart Pointers)是解决这类问题的银弹。 具体来说,对于动态分配的数组,你应该优先考虑使用
std::unique_ptr<T[]>
unique_ptr
delete[]
#include <memory>
#include <iostream>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructed\n"; }
~MyClass() { std::cout << "MyClass destructed\n"; }
};
void func() {
// 使用 std::unique_ptr<MyClass[]> 自动管理数组内存
std::unique_ptr<MyClass[]> arr = std::make_unique<MyClass[]>(3);
// arr[0], arr[1], arr[2] 可以正常使用
// ...
// 当 func 结束时,arr 会自动调用 delete[] 释放内存,并调用每个 MyClass 对象的析构函数
} // arr 在这里自动析构并释放内存
int main() {
func();
// 输出会显示 MyClass constructed 3次,然后 MyClass destructed 3次
return 0;
}如果你需要共享数组的所有权,
std::shared_ptr<T[]>
unique_ptr
new[]
delete[]
以上就是C++内存管理基础中new[]和delete[]使用规范的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号