作为这个问题的后续,根据[default.allocator]的规定,必须将默认分配器(
为什么†
std::allocator<T>
)的construct
实现如下:
也就是说,始终进行值初始化。这样做的结果是,对于任何pod类型,
template <class U, class... Args> void construct(U* p, Args&&... args);
Effects:
::new((void *)p) U(std::forward<Args>(args)...)
std::vector<POD> v(num)
将值初始化num
个元素 - 这比默认初始化num
个元素更昂贵。为什么†
std::allocator
没有提供默认初始化的附加重载呢?也就是说,类似于以下内容(从Casey借用):template <class U>
void construct(U* p) noexcept(std::is_nothrow_default_constructible<U>::value)
{
::new(static_cast<void*>(p)) U;
}
在这些情况下,为什么偏好于值初始化?这似乎令人惊讶,因为它违反了通常的C++规则,即我们只为我们想要使用的付费。
†我认为这样的改变是不可能的,因为目前std::vector<int> v(100)
会给你100个0
,但我想知道为什么会这样...既然同样可以要求std::vector<int> v2(100, 0)
,就像new int[100]
和new int[100]{}
之间存在差异一样。
vector
在这里的作用?它只是将算法添加到标准库中,对吗? - Barrymake_unique<T[]>
类似的问题。 - dyp