【问题标题】:std::allocator_traits::construct invokes wrong constructorstd::allocator_traits::construct 调用错误的构造函数
【发布时间】:2019-11-13 00:25:47
【问题描述】:

受到 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的搜索系统没有解决它。)

【问题讨论】:

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


    【解决方案1】:

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

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

    一定是:

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

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      相关资源
      最近更新 更多