c++ - C++11 是否要求分配器是默认可构造的,libstdc++ 和 libc++ 不同意?

标签 c++ c++11 language-lawyer libstdc++ allocator

使用稍作修改的 Howard Hinnants's C++11 stack allocator 版本这是 documented herehere ,使用 std::basic_string 并使用使用 libstdc++gcc 进行编译,以下示例 ( see it live ):

const unsigned int N = 200;

arena<N> a;
short_alloc<char, N> ac(a) ;

std::basic_string<char,std::char_traits<char>,short_alloc<char, N>> empty(ac);

给出以下错误(以及其他):

error: no matching function for call to 'short_alloc<char, 200ul>::short_alloc()'
   if (__n == 0 && __a == _Alloc())
                       ^

然而,当使用 clang 和使用 libc++ 编译时,它可以正常工作( see it live )。

std::basic_stringstdlibc++ 实现期望分配器具有默认构造函数。

C++11 是否要求分配器默认可构造?哪个实现是正确的?

最佳答案

不,C++11 不要求分配器具有默认构造函数,如果我们查看草案 C++11 标准部分 17.6.3.5 [allocator.requirements] 它包含表 28 分配器要求,其中不包含对默认构造函数的要求,稍后在本节中提供了一个最小的符合接口(interface):

[ Example: the following is an allocator class template supporting the minimal interface that satisfies the requirements of Table 28:

template <class Tp>
struct SimpleAllocator {
    typedef Tp value_type;
    SimpleAllocator(ctor args );

    template <class T> SimpleAllocator(const SimpleAllocator<T>& other);

    Tp *allocate(std::size_t n);
    void deallocate(Tp *p, std::size_t n);
};

—end example ]

不包含默认构造函数。

有一个 libstdc++ 错误报告:basic_string assumes that allocators are default-constructible其中说:

The empty-string optimization of basic_string assumes that allocators are default constructible. While this used to be the case in C++98, it is no longer true in C++11, as now allocators are allowed to have state.

Consider the attached example program. Compiling with

g++ -std=c++11 -c t.cpp

produces an error message, even though it should compile fine. The problem is the the "_S_construct" calls "_Alloc()", which does not exist.

Note that the C++11 standard does not require default constructors. (Section 17.6.3.5, Table 28). In particular, the SimpleAllocator example from Section 17.6.3.5 would trigger the same bug, too.

响应是:

This is hardly the only C++11 allocator requirement missing from std::string, ALL of the new requirements are missing, and unlikely to be implemented until we switch to a non-COW string implementation.

gcc 5.0 起已修复:

Fixed for GCC 5 (when using the new string ABI)

我们可以使用 gcc 5 on wandbox 确认这一点

关于c++ - C++11 是否要求分配器是默认可构造的,libstdc++ 和 libc++ 不同意?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29285322/

相关文章:

c++ - 将结构的动态数组复制到另一个结构

c++ - 为什么这不会将运算符重载标记为内联导致重复定义错误?

c++ - 移动选择的构造函数而不是复制。 [引用标准]

c++ - 从具有移动语义或返回值优化但不是复制构造函数的函数返回值

c++ - std::vector<type> 的类型要求

c++ - 包含常量成员的 POD 结构

c++ - 删除复制构造函数或复制赋值运算符是否算作 "user declared"?

c++ - 如何查找二维 vector 是否包含重复行?

c++ - 新的 int[size] 与 std::vector

c++ - 获得 Matlab <-> C++ 接口(interface)的最佳方法