没有为std:::string调用我的分配器中的select_on_container_copy_construction。当与vector tough一起使用时,它工作得很好。为什么行为会有所不同?这是不是GCC的bug?
我用的是gcc 5.4.0版本。
使用最小分配器的代码示例:
#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";
}
}程序应该同时打印“字符串工作”和“矢量工作”,但它只打印后者。
发布于 2018-12-19 23:42:13
这是this PR在6.1版本中解决的libstdc++中的一个错误。
具体的相关更改来自:
basic_string(const basic_string& __str)
: _M_dataplus(_M_local_data(), __str._M_get_allocator()) // TODO A traits至:
basic_string(const basic_string& __str)
: _M_dataplus(_M_local_data(),
_Alloc_traits::_S_select_on_copy(__str._M_get_allocator()))我不确定是否有开放的bug报告。我找不到一个,并且提交消息没有引用一个。
https://stackoverflow.com/questions/53852753
复制相似问题