C++0x: Explicit conversion operators

From wiki.dwarfstd.org
Jump to navigation Jump to search

For detail description of the feature, please refer to:



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
  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:
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


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


class Ptr
  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