如何在队列中存储 unique_ptr

How to store unique_ptr in a queue

我有这样一段代码,我尝试将 std::unique_ptr<T> 存储在 std::queue 中,但无法编译

#include "stdafx.h"
#include <windows.h>
#include <memory>
#include <string>
#include <iostream>
#include <deque>

using namespace std;

class Foo {
    std::string _s;
public:
    Foo(const std::string &s)
        : _s(s)
    {
        cout << "Foo - ctor";
    }

    ~Foo() {
        cout << "Foo - dtor";
    }

    void Say(const string &s) {
        cout << "I am " << _s << " and addtionaly " << s;
    }
};

typedef std::pair<long, std::unique_ptr<Foo>> MyPairType;
typedef std::deque<MyPairType> MyQueueType;

void Func(const std::unique_ptr<Foo> &pf) {
    pf->Say("Func");
}

void AddToQueue(MyQueueType &q, std::unique_ptr<Foo> &pF){
    MyPairType p;
    ::GetSystemTimeAsFileTime((FILETIME*)&p.first);
    p.second = pF; // **Fails here**
    q.push_back(p);
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::unique_ptr<Foo> pF(new Foo("Aliosa"));

    Func(pF);

    return 0;
}

它说我不能在AddToQueue方法中赋值。我知道这可能与 boost::shared_ptr 有关,但我们正试图摆脱 boost 依赖性,因此出现了这样的问题。

知道如何实现所需的行为吗? 谢谢

这一行:

p.second = pF;

正在制作唯一指针的副本(即它不再是唯一的)。您可以执行以下操作:

MyPairType p;
::GetSystemTimeAsFileTime((FILETIME*)&p.first);
p.second.swap(pF);
q.push_back(p);

但请记住,pF 将不再引用指针地址。如果您想要对同一地址的更多引用,您需要使用 std::shared_ptr.