【发布时间】:2018-03-09 08:57:36
【问题描述】:
选项 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++ 中使用哪个更好/更惯用。
【问题讨论】:
-
@FrançoisAndrieux:std::aligned_storage 不分配内存
-
@geza 是的。我评论的重点是建议分配
std::aligned_storage的实例而不是原始内存。该示例表明我们知道内存应该足够大以容纳一些T类型的对象。这是便携式解决方案。 -
@FrançoisAndrieux:
std::aligned_storage不是主要用于未分配的东西吗?operator new是否使用有关它分配的类型的信息?例如,它在分配存储时是否使用对齐信息?
标签: c++ memory malloc new-operator