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

标签 c++ constructor copy-constructor std-pair move-constructor

受到 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 的搜索系统无法解决这个问题。)

最佳答案

事实证明我错误地实现了移动构造函数:

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

必须是:

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

关于c++ - std::allocator_traits::construct 调用了错误的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58828649/

相关文章:

c++ - 代码中的疑问,测试赋值运算符的使用

C++ pistache 和 MJPEG 服务器

c++ - 你如何获得一个从右到左阅读的 vector ?

javascript - new Function() 和 new Function()() 之间的区别

java - 如果我们忽略新对象的结果会发生什么?

C++ copy-construct 构造和赋值问题

c++:转换运算符与赋值运算符与转换构造函数优先级

c++加解密源码

c++ - 为什么 C++ 类型表达式不是从左到右解释的?

c++ - c++错误c2440使用带有2d参数的构造函数