unique_ptr,std :: move和模板一起编译

时间:2015-04-11 05:40:47

标签: c++ c++11 move unique-ptr

我的编译器似乎讨厌unique_ptr,尤其是std::move。它永远不会编译我的代码。所以请帮助我或修复我的编译器。

template <typename T>
struct Message {
    std::unique_ptr<T> data;

    Message(std::unique_ptr<T>&& data):
    data(std::move(data)) {}
};

template<typename T>
class Queue {
    template<typename T2>
    struct QueueElement {
        T2 t;
        std::shared_ptr<QueueElement<T2>> next;
    };

    std::shared_ptr<QueueElement<T>> first;
    std::shared_ptr<QueueElement<T>> last;

public:
    Queue():
    first(new QueueElement<T>), last(first) {}

    void In(T& t) {
        last->t = t;
        last->next = std::make_shared<QueueElement<T>>;
        last = last->next;
    }

    T Out() {
        T t = first->t;
        first = first->next;
        return t;
    }
};

int main() {
    Queue<Message<std::string>> messageQueue;
    std::unique_ptr<std::string> stringPointer(new std::string);
    messageQueue.In(Message<std::string>(std::move(stringPointer)));
    return 0;
}

1 个答案:

答案 0 :(得分:1)

我假设你得到了一个c ++ 11编译器。

template <typename T>
struct Message {
    std::unique_ptr<T> data;
    Message(){} // 1. add default constructor, as you have a customer constructor, compiler will not define the default constructor automatically
    Message(std::unique_ptr<T>&& data):
    data(std::move(data)) {}

    //2, a simple move assignment
    Message& operator=(Message && r)
    {
        data = std::move(r.data);
        return *this;
    }
};

3.像这样改变In

void In(T&& t) {
    last->t = std::move(t);
    last->next = std::make_shared<QueueElement<T>>;
    last = last->next;
}