Search code examples
c++c++11iostreamsmart-pointersunique-ptr

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?


Solution

  • 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.