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

问题描述 投票:0回答:1

出于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;
        }
        // ...
    };
}

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

我不明白。 construct具有转发引用作为参数,std::pair的构造函数也是如此。因此,应完整交付std::move中的右值引用。那为什么会这样呢?

((如果这是一个骗子,我很抱歉。StackExchange的搜索系统没有删减它。)

c++ constructor copy-constructor std-pair move-constructor
1个回答
0
投票

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

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

必须是:

forward_list(
    forward_list &&other
) : forward_list(move(other), other.alloc) {}
© www.soinside.com 2019 - 2024. All rights reserved.