Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 7.0.2: operator const char *()
#1
Hello,

Rule 7.0.2 has an exception for converting pointer to bool, and requires an explicit operator bool() for classes. But what if a class, let's say a wrapper class for strings, provides an operator const char *? Consider the following example:

Code:
class C
{
public:
    operator const char *() const;
};

void f(C c)
{
    if (c); // C is converted twice: C -> const char * -> bool
}

Shall the commented line be considered compliant with this rule (because each of the conversion steps by itself is compliant), or not (because as a whole it is the conversion of a class to bool without using an explicit operator bool)?
Reply
#2
The later, it should be treated as non-compliant. In effect you've got an object of type C being converted to bool, even if it does go through extra steps.

if (c.operator()) ;
  or
if ( c );  // if C declared operator bool();
would both be compliant.
Posted by and on behalf of
the MISRA C++ Working Group
Reply
#3
Alright, thank you very much for the clarification.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)