Stream and implicit function call void * cast

code like

cin>> grade; 

where the class is a standard data type, returns a reference to cin (an istream object), which allows cascading inputs ....
but I read that if

 cin >>grade; 

it is used as a condition that says in the while statement ... the void * cast stream operator is called implicitly ... and it converts the reference to the istream object to a non-zero or null pointer depending on success or failure, the last input operation ... and the null pointer is converted to false and not null to true ... my questions are:

  • what is the function of the void * cast operator and how it works here.
  • how an invalid pointer is converted to true and null to false
+6
source share
1 answer

1. What is the function of the void * cast operator and how does it work here.

It looks something like this:

 operator void* () const { return fail() ? 0 : this; } 

The question is why operator bool is not used here? The answer is: because it allows you to use incorrect conversions that can hide errors. The above example is a safe bool identifier .

However, this implementation is actually out of date. There are better implementations of this idiom; article explains them.

2.how is a non-null pointer converted to true and null to false

This is exactly how C ++ works: any non-zero pointer is considered equivalent to true in the conditional expression. So why does C ++ refer to operator void* here in the first place?

Essentially, when C ++ sees an object of an unexpected type, it tries to apply one implicit conversion that will make the type of the object valid in this context. Therefore, the compiler checks all available implicit conversions and looks to see if the resulting type is acceptable in this context.

This happens with her: the compiler sees while (cin >> grade) . He knows that basic_istream not valid in the context of the while condition. Thus, it discovers that operator void* exists, and a void* is valid in this context, therefore C ++ applies this transformation.

+10
source

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


All Articles