Restrain Conversion Operators with the “Indirect Conversion” Idiom

Restrain Conversion Operators with the “Indirect Conversion” Idiom

onversion operators are a dilemma. While they certainly make the usage of certain objects convenient and intuitive, they also compromise type safety, ultimately leading to unexpected runtime behavior. The following sections present a technique that significantly reduces the potential hazards of implicit conversions to bool. This technique is now becoming a de-facto standard in C++ libraries, like Boost.


You want to add a conversion operator to your class, but you’re concerned about the perils of implicit conversions.


Use the “indirect conversion” idiom to thwart undesirable conversions while still permitting well-behaved conversions.

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 Ptr{public: operator bool() const {  return (rawptr ? true: false); }//..more stuffprivate: T * rawptr;};

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

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

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

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

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

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

booling Around
In the pre-bool era, C++ libraries often used void* as the target type of a Boolean conversion operator. The library is an example of this. Will void* save the day? Indeed, a void* conversion operator prevents nonsensical expressions such as p1+p2 from compiling:

template class Ptr{public: operator void*() const {  return ((void*) rawptr); }};cout<<"p1 + p2 = "<< p1+p2 < pf;Ptr  pq; // Query and File are unrelated typesif(pf==pq) // so so, compares raw addresses 

And yet, a void* conversion operator introduces new surprises:

cout << pf <

The Pointer to Member Hack
Recently, C++ pundits have come up with a better idea. Instead of using bool or void*, classes such as std::tr1::shared_ptr use pointers to members as the target type of a Boolean conversion operator.

Author's Note: The terms "conversion to bool" and "conversion to Boolean" aren't interchangeable. In the former, bool is the target type. The latter however uses an unspecified type that's convertible to bool.

Let's look at a concrete implementation of this technique.

First, add a nested struct that has one data member to class Ptr (code changes are highlighted):

template class Ptr{private: struct PtrConversion {  int valid; };};

Next, declare a typedef that serves as a synonym for "pointer to an int member of PtrConversion":

template class Ptr{private: struct PtrConversion {  int valid; };public: typedef int PtrConversion::*pmi;};

Finally, define a public conversion operator whose target type is pmi:

public:operator pmi() const //conversion to Boolean { return rawptr? &PtrConversion::valid : 0;}

Smooth Operator
Let's analyze the return statement. If rawptr isn't NULL, the conversion operator returns a pointer to a member of struct PtrConversion (the precise value of the expression &PtrConversion::valid is immaterial; what matters is that it's a non-NULL constant). However, if rawptr is NULL, the conversion operator returns a NULL pmi. Recall that all pointers to members are implicitly convertible to bool; they aren't bool variables, though. This subtle difference is crucial, as you will see.

After this change, when the following statement executes:

if(ptr)//...

C++ calls ptr.operator pmi() behind the scenes. The return value of type pmi is then silently converted to bool, as expected. However, the following statement no longer compiles, which is exactly what you want:

cout<<"p1 + p2 = "<< p1+p2 <

Here's the secret: C++ guarantees that an operand shall undergo at most one implicit conversion. In the if(ptr) example, you have exactly one implicit conversion from pmi to bool (the very invocation of a conversion operator doesn't constitute an implicit conversion for this matter). However, in the expression p1+p2 two implicit conversions per operand are necessary:

  1. pmi?>bool
  2. bool?>int

As I said, C++ doesn't allow this.

Let's see how this technique eliminates the problems caused by a void* conversion operator:

cout << pf <

This statement no longer compiles since there is no overloaded version of operator << that takes pmi or Ptr. Similarly, the following delete expression:

delete pf; //compilation error

doesn't compile because neither pmi nor bool are valid types in a delete expression.

Twisting by the bool
The boost::shared_ptr class uses a slightly different version of the indirect conversion technique. Instead of using a dummy nested struct, it uses a pointer to a member of class shared_ptr itself. In terms of memory footprint, there is no difference between the two versions because the dummy struct is not instantiated anyway. However, some compilers have difficulties coping with pointers to member functions of a class template so the Boost library uses conditional compilation to switch between a pointer to a data member and a pointer to a member function as the target type of the Boolean conversion operator. The bottom line is this: instead of bool, void* or int as the target type of a Boolean conversion operator, use a pointer to member to minimize the perils of implicit conversions.

devx-admin

devx-admin

Share the Post:
USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap