Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing unique_ptr to cout

Not able to understand why this is failing?

int *p = new int(10);
std::unique_ptr<int> ptr(p);
// Below line gives compilation error.
std::cout << "Value of ptr        " << ptr << std::endl;
// Below line works well.
std::cout << "Value pointed ptr   " << *ptr << std::endl;
std::cout << "Value of ptr->get() " << ptr.get() << std::endl;

I understand it this way:

Say address of p is 100, address of new allocated memory is 200.

p                new allocated memory
----------       ---------
   200              10
----------       ---------
100              200


ptr
----------
   200
----------
300

In above depiction, unique_ptr is pointing to newly allocated memory itself, avoiding 'p'. So, should not printing 'ptr' give me 200?

like image 725
Hemant Bhargava Avatar asked Feb 09 '17 11:02

Hemant Bhargava


1 Answers

std::unique_ptr<int> ptr(p);
// Below line gives compilation error.
std::cout << "Value of ptr        " << ptr << std::endl;

To make it possible to use the usual << syntax to print an object of some class using cout, there must be a proper overload of operator<< implemented.

For example, if you have a class X, if you want to enable the cout << x syntax, you can overload operator<< like this:

#include <ostream> // for std::ostream

std::ostream& operator<<(std::ostream& os, const X& x)
{
  // Implement your output logic for 'x'
  ...

  return os;
}

The C++ standard library designers chose not to implement such an overload for std::unique_ptr; this is why you get the compilation error when you try to use << with instances of unique_ptrs.

like image 133
Mr.C64 Avatar answered Sep 17 '22 14:09

Mr.C64