哪一种是在C 中分配非初始化内存的最惯用方法
Which one is the most idiomatic way to allocate uninitialized memory in C++
选项A:
T * address = static_cast<T *>(::operator new(capacity * sizeof(T), std::nothrow));
选项B:
T * address = static_cast<T *>(std::malloc(capacity * sizeof(T)));
上下文:
template <typename T>
T * allocate(size_t const capacity) {
if (!capacity) {
throw some_exception;
}
//T * address = static_cast<T *>(std::malloc(capacity * sizeof(T)));
//T * address = static_cast<T *>(::operator new(capacity * sizeof(T), std::nothrow));
if (!address) {
throw some_exception;
}
return address;
}
std::malloc
较短,但是::operator new
显然是C ,并且可能是通过std::malloc
实现的。哪一个更好/更多的惯用性在C 中使用。
如果可能的话,您应该希望以类型安全的方式分配内存。如果这是不可能的,请选择选项A,operator new(size_t, std::nothrow)
,因为:
- 运算符
new
和delete
可以合法地覆盖(这在自定义分配器/泄漏检测方案中很有用)。 - 可以有一个替代分配器来处理低内存(
set_new_handler
)。 - 更多的C 。
首选malloc
/free
的唯一原因是,如果您想用realloc
优化 Reallocations ,而operator
new
/delete
(Realloc不是一个简单的免费 malloc)。/p>
相关文章:
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 使 std::vector 分配对齐内存的现代方法
- 内存效率表示最短路径的方法?
- 一种从内存中删除 UTF 字节的方法?
- 删除类成员的动态分配内存的最佳方法是什么
- 在指向现有内存地址的 hpp 文件中声明成员函数的最佳方法
- 释放 std::vector 中指针内存的最有效方法是什么?
- 有什么方法可以识别可用的内存地址吗?
- avcodec_open2方法中的 FFMPEG 内存泄漏
- 组织从内存读取的数据的最佳方法(用于调试)c++
- 识别打开的共享内存状态的方法
- 释放分配给大量矢量的内存的最有效方法是什么?
- 为大无符号整数分配内存的有效方法
- C ++中新分配的int的内存大小,有没有不同更好的方法来查看它?
- 将两位数字转换为低内存表示的最快方法
- 使用删除与智能指针释放内存以及释放内存的正确方法
- C ++中的几种分配内存方法有什么区别
- 游戏循环中的可变内存方法范围