vector of unique_ptr

I tried to make a vector of unique_ptrs, but here I get a compiler error when I try to dereference the ptr:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <memory>
#include <vector>

struct Person
{
    std::string mName;
    int mAge;
    Person() : mName("Joe Sixpack"), mAge(40) {}
    Person(std::string & name, int age) : mName(name), mAge(age) {}
};

int main()
{
  std::vector<std::unique_ptr<Person>> v(20);
  
  for( std::unique_ptr<Person> & p : v )
      p = std::unique_ptr<Person>(new Person);
  
  for( std::unique_ptr<Person> & ptr : v )
      std::cout << *ptr << "; ";
}


Here the compiler's error message:
1
2
3
4
5
6
21:21: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
In file included from /usr/include/c++/4.9/iostream:39:0,
                 from 1:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = Person]'
     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
     ^

Last edited on
The error has nothing to do with the use of unique_ptr.

The problem is that you are passing a Person object as argument to the << operator. You either have to overload the << for the Person class, or pass each member that you want to print individually.
Last edited on
Oh, what a silly mistake. I ask me how I could this simple fact having overlooked.
Also a quick tip. When making a unique_ptr, you can also use the std::make_unique() function. For example, line 18 could be rewritten like this (changing the class name):

1
2
3
4
5

p = std::unique_ptr<ThisIsAVeryLongClassName> (new ThisIsAVeryLongClassName); //awkward

p = std::make_unique<ThisIsAVeryLongClassName>(); //clean


With the first method, you have to specify the type twice, which can be confusing and cumbersome if the class has a long name.
Topic archived. No new replies allowed.