Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Use Explicit Conversion Functions to Avert Reckless Implicit Conversions

Conversion functions are inherently unsafe as they might surprise you with implicit conversions over which you have no control. This is why such functions have been avoided for years. Learn how the new C++0x explicit conversion functions put an end to years of conversion functions blues.


advertisement

he compiler invokes user-defined conversion functions (which are also called conversion operators) implicitly. In most cases, this process is well-behaved and intended. However, there are cases when you certainly don't want the compiler to invoke the conversion operator implicitly—but you can't prevent it. Several workarounds have been devised to mitigate this problem, including the indirect conversion idiom. And yet, these workarounds are neither intuitive nor perfect. C++0x finally brings a radical solution in the form of explicit conversion functions.


Your class defines a conversion function to a certain type. You want to ensure that this function will be invoked only when appropriate.


Declare conversion functions explicit, thus forcing clients to use casts explicitly.



Presenting the Problem
The problematic nature of unrestrained conversion functions is clearly demonstrated in smart pointers. Class std::shared_ptr defines an implicit conversion to an implementation-defined Boolean type. As you may recall, the "implementation-defined Boolean type" is actually a pointer to a data member, not the built-in booltype:


template <class T>
class Ptr
{
private:
 struct PtrConversion
 {
  int valid;
 };
public:
 operator PtrConversion::*pmi() const//Boolean conversion
 {
  return rawptr? &PtrConversion::valid : 0;
 }
};

As ugly as this kludge may seem, it does prevent awful bugs like these:


Ptr p1, p2;
cout<<"p1 + p2 = "<< p1+p2 <<endl; 

Ptr <File> pf;
Ptr <Query> pq; //Query and File are unrelated types
if(pf==pq)... //compares raw pointers, not objects!

There are, however, other ailments that the indirect conversion idiom cannot cure.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap