标准说,在 5.3.4[expr.new]/7
When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.
并且在 3.7.3.1[basic.stc.dynamic.allocation]/2
The effect of dereferencing a pointer returned as a request for zero size is undefined.
但是如果分配函数是用户定义的并且它知道它返回了一个有效的指针,那么取消引用它仍然是未定义的行为吗?标准可以强制执行用户代码的未定义行为吗?
我问的原因是又一次毫无意义的尝试初始化非默认可构造类型的对象的动态数组。除了明显缺少delete[]
并且只能用[0]
调用外,它还有什么问题?我是否正确使用了 aligned_storage
?
#include <type_traits>
#include <stdexcept>
#include <memory>
#include <iostream>
struct T {
int val;
T() = delete;
T(int i) : val(i) {}
void* operator new[](std::size_t, std::size_t cnt, const T& t)
{
typedef std::aligned_storage<sizeof(t),
std::alignment_of<T>::value>::type buf;
T* ptr = reinterpret_cast<T*>(new buf[cnt]);
std::uninitialized_fill_n(ptr, cnt, t);
return ptr;
}
};
int main()
{
T* a = new(100, T(7)) T[0]; // using zero is legal per 5.3.4/7
std::cout << "a[0] = " << a[0].val << '\n' // but is this legal?
<< "a[1] = " << a[1].val << '\n'
<< "a[98] = " << a[98].val << '\n'
<< "a[99] = " << a[99].val << '\n';
delete[] a; // free the 100 aligned_storages
}
使用 MSVC++ 2010 EE 也能按预期编译和运行
最佳答案
您的代码中存在令人恼火的逻辑问题:
新的表达方式:
T* a = new(100, T(7)) T[0];
调用 T 的已删除默认构造函数 [expr.new]/17。 ;-(
std::vector<T>
现在肯定看起来不错...... :-)
关于c++ - new(size, value) Type[0] 返回的指针是否合法,是否可以用于构建数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5559525/