如何在代码中使用"new"而不是"malloc"
How to use 'new' insted of 'malloc' in code
我的代码如下所示
SP->xs = malloc(size * sizeof(double));
其中xs
是结构变量,size
是int
类型,
所以在这里我如何使用new
而不是malloc
我应该包含哪个头文件? 以及这个新行的语法将如何变成?
我只是像下面一样尝试了一下
SP->xs = operator new sizeof(double)*[size];
当我编译此代码时,会出现如下错误
error: cannot resolve overloaded function 'operator new' based on conversion to type 'double*'
error: expected ';' before 'sizeof'
因为我是新手C++所以我不知道更多细节,
所以请描述我如何在我的代码中使用new
而不是malloc
感谢和问候
相当于
SP->xs = malloc(size * sizeof(double));
是
SP->xs = new double[size];
这不需要任何#include
。
要释放分配的数组,请使用delete[]
:
delete[] SP->xs;
方括号很重要:没有它们,代码将编译,但将具有未定义的行为。
由于您是用C++编写的,请考虑使用 std::vector<double>
而不是手动管理内存分配。
相关文章:
- 在使用malloc/new时无法编译stm32l4r5xx
- 如何使用 "new" 而不是 malloc 分配内存?
- Malloc vs New for Primitives
- 在C++中调用 malloc() 与"operator new"函数之间的实现差异
- 供应商是否将 new 和 malloc 实现为小型对象分配器
- 无法调用使用 malloc/placement new 创建的类上的虚函数
- 使用 new 而不是 malloc 分配 mem
- 使用 malloc 而不是 new 会导致 free():指针错误无效
- 正在使用new char[]或malloc的结果来铸造float*是UB(严格的混叠冲突)
- 此测试是否证明 malloc、calloc、new 在我的系统上管理自己的内存池?
- `delete []`on`int*````new'''给出了malloc错误
- 在混合 C/C++ 程序中协调 malloc 和 new 的"正确"方法是什么?
- 构造函数中的 Malloc 在通过 New 调用时返回 NULL
- 在 C++ 中将 malloc/free 替换为 new/delete
- "new int[5]"和"malloc(5 * sizeof(int))"之间的C++有什么区别?
- 如果通过委托给“malloc”的重载“new[]”分配,“释放”内存是否安全
- “new/malloc”应该“delete/free”的人
- 使用运算符 new/malloc 分配的内存块是否可以在程序执行结束后持续存在
- 当退出 new/malloc 函数时,从 new/malloc 返回的指针如何保持在范围内
- new/malloc 似乎如何记住分配的数据量