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

Does C++11 require allocators to be default constructible, libstdc++ and libc++ disagree?

使用 Howard Hinnants's C++11 stack allocator which is documented here and here, with std::basic_string and compiling with gcc which is using libstdc++, the following example (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())
                       ^

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

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

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

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

[ 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

来确认这一点