GCC中的libstdc ++的basic_string实现和自定义指针

问题描述 投票:1回答:1

我最近尝试研究libstdc ++源代码(GCC 7.2)并且感到困惑。可能我错过了一些重要的东西,但我开始认为实现完全符合C ++标准的basic_string类是不可能的。

这是我遇到的一个问题。

  1. basic_string应该能够接受自定义分配器类作为模板参数。
  2. 需要allocate方法作为分配器的一部分。
  3. 允许allocate返回用户定义类型的对象,其“就像指向已分配数据的指针”。我们称之为my_pointer。
  4. my_pointer应该只满足NullablePointer和RandomAccessIterator的要求。所有其他要求都是可选的。根据标准,我们可能无法将my_pointer转换为CharT *类型(另一个basic_string模板参数),因为它是可选的。
  5. 另一方面,const CharT * c_str()方法应作为标准的一部分实现,因此我们必须知道如何进行此转换。

第4项和第5项是冲突的,我不知道如何解决它。希望你能帮助我搞清楚。

谢谢!

c++ pointers language-lawyer stdstring allocator
1个回答
2
投票

该标准有几个要求,它们总是确保转换是可能的,至少是间接的

  1. 鉴于basic_­string<charT, traits, Allocator>the standard requires charTallocator_traits<Allocator>::value_type是平等的。
  2. qazxsw poi qazxsw poi要么是qazxsw poi,要么是qazxsw poi。 在前一种情况下,给予allocator_traits<Allocator>::pointer is requiredAllocator::pointer Allocator::value_type*Allocator::pointer。 在后一种情况下,一切都是微不足道的。
  3. p *p是一个is required,这要求,给定一个连续的迭代器Allocator::value_type&Allocator::pointer
  4. 鉴于is required contiguous iteratorq *(q + n) == *(addressof(*q) + n)返回Allocator

将所有内容组合在一起,就意味着这始终是正确的

a

a.allocate(n)可能存储前一次调用is required的结果

© www.soinside.com 2019 - 2024. All rights reserved.