Search code examples
c++c++11c++14stdstringallocator

select_on_container_copy_construction not called for std::string


select_on_container_copy_construction in my allocator is not called for std:::string. It works fine when used with a vector tough. Why is the behavior different? Is this a bug in GCC?

I am using gcc version 5.4.0.

Code example with a minimal allocator:

#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";
  }
}

The program should print both "string worked" and "vector worked", but it only prints the latter.


Solution

  • This was a bug in libstdc++ that was resolved in the 6.1 release by this PR.

    The specific relevant change was from:

    basic_string(const basic_string& __str)
    : _M_dataplus(_M_local_data(), __str._M_get_allocator()) // TODO A traits
    

    to:

    basic_string(const basic_string& __str)
    : _M_dataplus(_M_local_data(),
        _Alloc_traits::_S_select_on_copy(__str._M_get_allocator()))
    

    I'm not sure if there was an open bug report. I can't find one and the commit message doesn't reference one.