如何将unique_ptr存储在队列中

时间:2015-01-06 06:11:02

标签: c++ boost stl

我有这样的代码,我尝试在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依赖性,从而产生这样的问题。

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

1 个答案:

答案 0 :(得分:4)

这一行:

p.second = pF;

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

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

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

相关问题