gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:37:29 25 4
gpt4 key购买 nike

使用稍作修改的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com