Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Restrain Conversion Operators with the "Indirect Conversion" Idiom-2 : Page 2




Application Security Testing: An Integral Part of DevOps

Presenting the Problem
Suppose you're designing a smart pointer class. In addition to overloading the operators * and ->, a smart pointer class usually defines a conversion operator to bool:

template <class T> class Ptr { public: operator bool() const { return (rawptr ? true: false); } //..more stuff private: T * rawptr; };

The conversion to bool enables clients to use smart pointers in expressions that require bool operands:

Ptr<int> ptr(new int); if(ptr ) //calls operator bool() cout<<"int value is: "<<*ptr <<endl; else cout<<"empty"<<endl;

Furthermore, the implicit conversion to bool is required in conditional declarations such as:

if (shared_ptr<X> px = dynamic_pointer_cast<X>(py)) { //we get here only of px isn't empty }

Alas, this automatic conversion opens the gate to unwelcome surprises:

Ptr <int> p1; Ptr <double> p2; //surprise #1 cout<<"p1 + p2 = "<< p1+p2 <<endl; //prints 0, 1, or 2 Ptr <File> pf; Ptr <Query> pq; // Query and File are unrelated //surprise #2 if(pf==pq) //compares bool values, not pointers!

Comment and Contribute






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



Thanks for your registration, follow us on our social networks to keep up-to-date