首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未为std::string调用select_on_container_copy_construction

未为std::string调用select_on_container_copy_construction
EN

Stack Overflow用户
提问于 2018-12-19 21:55:35
回答 1查看 122关注 0票数 0

没有为std:::string调用我的分配器中的select_on_container_copy_construction。当与vector tough一起使用时,它工作得很好。为什么行为会有所不同?这是不是GCC的bug?

我用的是gcc 5.4.0版本。

使用最小分配器的代码示例:

代码语言:javascript
复制
#include <iostream>
#include <vector>

template<class T>
class allocator {
public:
  typedef T value_type;

  using propagate_on_container_copy_assignment = std::true_type; // for consistency
  using propagate_on_container_move_assignment = std::true_type; // to avoid the pessimization
  using propagate_on_container_swap = std::true_type; // to avoid the undefined behavior

  allocator<T> select_on_container_copy_construction() const {
    throw std::bad_alloc();
  }

  T *allocate(const std::size_t n) {
    return static_cast<T *>(::operator new(n * sizeof(T)));
  }

  void deallocate(T *, const std::size_t) { }
};

template< class T1, class T2 >
bool operator==(const allocator<T1>&, const allocator<T2>&) noexcept {
  return true;
}

template< class T1, class T2 >
bool operator!=(const allocator<T1>&, const allocator<T2>&) noexcept {
  return false;
}

int main()
{
  try {
    std::basic_string<char, std::char_traits<char>, allocator<char>> s;
    auto ss = s;
  } catch (std::bad_alloc const&) {
    std::cout << "string worked\n";
  }

  try {
    std::vector<int, allocator<int>> v;
    auto vv = v;
  } catch (std::bad_alloc const&) {
    std::cout << "vector worked\n";
  }
}

程序应该同时打印“字符串工作”和“矢量工作”,但它只打印后者。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-19 23:42:13

这是this PR在6.1版本中解决的libstdc++中的一个错误。

具体的相关更改来自:

代码语言:javascript
复制
basic_string(const basic_string& __str)
: _M_dataplus(_M_local_data(), __str._M_get_allocator()) // TODO A traits

至:

代码语言:javascript
复制
basic_string(const basic_string& __str)
: _M_dataplus(_M_local_data(),
    _Alloc_traits::_S_select_on_copy(__str._M_get_allocator()))

我不确定是否有开放的bug报告。我找不到一个,并且提交消息没有引用一个。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53852753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档