2

I have such a code, where I try to store a std::unique_ptr<T> in a std::queue but it won't compile

#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; } 

It says that I cannot assign in the method AddToQueue. I know this is possible to do with boost::shared_ptr but we are trying to get rid of boost dependency thus having such issue.

Any idea how to achieve the needed behavior? thx

0

1 Answer 1

4

This line:

p.second = pF; 

is making a copy of a unique pointer (ie it is no longer unique). You can do the following:

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

But remember that then pF will no longer reference the pointer address. If you want more references to the same address you need to use std::shared_ptr.

Sign up to request clarification or add additional context in comments.

1 Comment

shared_ptr this is the guy I need to use. Thx!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.