c++ - new(size, value) Type[0] 返回的指针是否合法,是否可以用于构建数组?

标签 c++ c++11 standards-compliance array-initialization

标准说,在 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
}

试运行:http://ideone.com/iBW0z

使用 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/

相关文章:

C++ : compile time assert the value of a floating point number

c++ - 如何使 boost-proto 函数表达式可流化?

c++ - Boost 将默认边权重设置为 1

c++ - 转发引用 : returning T when given T&& and T& when given T&

c++ - 如何在没有 Singleton 的情况下实现方便的日志记录?

c - G.711 实现 A 律

c++ - 乘法宏给出错误的答案

c++ - 为什么 std::move 表现得像 std::copy?

c++ - 从 'ClassType<std::unique_ptr<Base>>' 创建 'std::unique_ptr<Derived>' 时出现 (/permissive-) 的编译错误

cookies - HTTP 状态管理机制 (Cookies) 的当前状态