1

I have some code:

#include <string>
#include <memory>
#include <queue>

template <typename T>
class MyQueue {
  public:
  MyQueue() {
    q_(new std::queue<T>);
  }

  private:
  std::unique_ptr<std::queue<T>> q_; 
};

int main() {
  MyQueue<std::string> queue;
  return 0;
}

When I compile with g++ (-std=c++11) I get an output that indicates that I am not constructing my unique_ptr properly. What is the 'proper' way to construct such a unique_ptr?

The output:

test.cc: In instantiation of ‘MyQueue<T>::MyQueue() [with T = 
    std::__cxx11::basic_string<char>]’:
test.cc:18:24:   required from here
test.cc:9:5: error: no match for call to 
    ‘(std::unique_ptr<std::queue<std::__cxx11::basic_string<char>, 
std::deque<std::__cxx11::basic_string<char>, 
std::allocator<std::__cxx11::basic_string<char> > > >, 
std::default_delete<std::queue<std::__cxx11::basic_string<char>, 
std::deque<std::__cxx11::basic_string<char>, 
std::allocator<std::__cxx11::basic_string<char> > > > > >) 
(std::queue<std::__cxx11::basic_string<char>, 
std::deque<std::__cxx11::basic_string<char>, 
std::allocator<std::__cxx11::basic_string<char> > > >*)’
     q_(new std::queue<T>);
     ^
chub500
  • 712
  • 6
  • 18
  • 2
    "I get an output that indicates" you should keep actual error message a secret, that will make it more interesting for others to guess – Slava Feb 01 '18 at 19:45
  • When I make a std::unique_ptr, I use `std::make_unique`. – Eljay Feb 01 '18 at 19:47
  • You need to use proper syntax for member initialization list. – Slava Feb 01 '18 at 19:49
  • Could someone explain to me how this linked question is similar? – chub500 Feb 01 '18 at 19:49
  • I already explain - you try to call `q_` as a function, you need to use "member initilization list", it is fully explained there. – Slava Feb 01 '18 at 19:51
  • I don't think the question is actually a duplicate - rather, the answer to this question is "use an initializer list" – Phydeaux Feb 01 '18 at 19:51
  • Why do you use a unique_ptr at all? Simply use the std::queue. –  Feb 01 '18 at 19:53
  • 1
    @Eljay Question is tagged `c++11`. [std::make_unique](http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique) was introduced with C++ 14. Not hard to write your own, though. – Mateusz Grzejek Feb 01 '18 at 19:53
  • @Phydeaux maybe it is not a full dupe, but header sais: "This question already has an answer here:" which is true. – Slava Feb 01 '18 at 19:55
  • I understand now, thank you @Slava. I would argue that this is not an obvious duplication, even if the answer is in the other question :). – chub500 Feb 01 '18 at 19:56
  • @Slava but the **answers** to the linked question will not help OP at all – Phydeaux Feb 01 '18 at 19:57
  • Agreed, this does not seem to be a duplicate at all. – Jedi Feb 01 '18 at 21:02

0 Answers0