C++0x: Explicit conversion operators

From Dwarf Wiki
Jump to: navigation, search

For detail description of the feature, please refer to:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2380.pdf


Overview

Standard C++ added the explicit keyword as a modifier on constructors to prevent single-argument constructors to be used as implicit type conversion operators. C++0x permits the explicit to be applied to the definition of a user-defined conversion operator. The purpose is to prevent use of user-defined conversion operators in implicit conversions.

Consider the smart pointer class:

template <class T> class Ptr
{
public:
  operator bool() const { ... }
}

The purpose of the bool() operator is to verify if the pointer is valid:

Ptr<int> smart_ptr (&some_var);
if (smart_ptr) {
  // pointer is valid
} else {
  // pointer is invalid
}

However, the bool() operator also allow compiler to compile the following code:
<pre>
Ptr<int>   p1;
Ptr<float> p2;

std::cout << p1 + p2 << std::endl;   // bool() operator invoke and convert to int.
                                     // but what does p1+p2 mean?

Adding the explicit keyword for the operator bool(), will disallow the above conversion.


Proposed change to DWARF

none.

The exising DW_AT_explicit attribute can be applied to the operator as well.


Example

class Ptr
{
public:
  explicit operator bool() const { ... }
}

<1><  ###>      DW_TAG_class_type
                DW_AT_name                  Ptr
<2><  ###>      DW_TAG_subprogram           
                DW_AT_type                  <xxx>   // bool
                DW_AT_name                  operator()
                DW_AT_explicit              yes