Print unique_ptr in cout

It is impossible to understand why this fails?

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; 

As I understand it:

Let's say address p is 100, the address of the new allocated memory is 200.

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

In the above description, unique_ptr points to newly allocated memory, avoiding "p". So shouldn't print "ptr", give me 200?

+6
source share
2 answers
 std::unique_ptr<int> ptr(p); // Below line gives compilation error. std::cout << "Value of ptr " << ptr << std::endl; 

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

For example, if you have class X, if you want to include the syntax cout << x , you can overload operator<< as follows:

 #include <ostream> // for std::ostream std::ostream& operator<<(std::ostream& os, const X& x) { // Implement your output logic for 'x' ... return os; } 

The designers of the C ++ standard library decided not to implement such an overload for std::unique_ptr ; therefore, you get a compilation error when you try to use << with unique_ptr s instances.

+9
source

So shouldn't type 'ptr' give me 200?

It should, if the standard library specified by std::unique_ptr should be streamed in standard streams. In other words, there must be an operator << overload for std::unique_ptr .

However, the standard does not indicate such a thing, so the unique_ptr results in a compilation error (no operator << accepts it). The solution is as you found: if you need to pass a pointer, get a pointer:

 stream << ptr.get() 
+2
source

Source: https://habr.com/ru/post/1014836/


All Articles