std::allocator_traits::construct调用了错误的构造函数

std::allocator_traits::construct invokes wrong constructor

本文关键字:错误 构造函数 调用 construct allocator traits std      更新时间:2023-10-16

受到Haskell的启发,我尝试实现这样的std::forward_list

namespace std {
template <class T, class Allocator = allocator<T>>
class forward_list {
typename allocator_traits<Allocator>::template rebind_alloc<pair<forward_list<T>,T>> alloc;
typename allocator_traits<decltype(alloc)>::pointer ptr;
public:
// ...
void push_front(const T &value) {
auto newPtr = allocator_traits<decltype(alloc)>::allocate(alloc, 1);
allocator_traits<decltype(alloc)>::construct(alloc, newPtr, move(*this), value);
ptr = newPtr;
}
// ...
};
}

但是push_front中的construct调用复制构造函数,而不是移动构造函数。

我不明白。construct具有作为参数的转发引用,std::pair的构造函数也是如此。因此,来自std::move的右值引用应该完好无损地传递。那么,为什么会发生这种情况呢?

(如果这是一个骗局,我很抱歉。Stack Exchange的搜索系统没有切断它。(

原来我错误地实现了move构造函数:

forward_list(
forward_list &&other
) : forward_list(other, other.alloc) {}

必须是:

forward_list(
forward_list &&other
) : forward_list(move(other), other.alloc) {}