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

萝らか妹 提交于 2019-11-28 23:46:28

No, C++11 does not require an allocator have default constructor, if we look at the draft C++11 standard section 17.6.3.5 [allocator.requirements] it contains Table 28 Allocator requirements which does not contain a requirement for a default constructor and later on in the section a minimal conforming interface is provided:

[ 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 ]

which does not contain a default constructor.

There is a libstdc++ bug report: basic_string assumes that allocators are default-constructible which says:

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.

and the response was:

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.

This is fixed as of gcc 5.0:

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

We can confirm this using gcc 5 on wandbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!