devxlogo

Protect Smart Pointers by Providing Multiple Interfaces

Protect Smart Pointers by Providing Multiple Interfaces

In general, when a smart pointer is designed, the usual methods proivided are: T* operator->() const and T operator*() const. So, in functions such as foo(const SmartPointer& ptr) { }, what is meant by “const“? You can’t reassign ptr, of course?and further, you can only call const methods on the pointer itself. The method T* operator->() const can be called on ptr. Once dereferenced, you can call any method on the underlying protected object including non-const methods. Not what you expected?

Here is how you can declare your methods: assume that the smart pointer protects only one object. That object, however, has two interfaces which it implements: A “mutable” and an “immutable” interface. You then declare the methods as follows:

Mutable* operator->();

and

Immutable* operator->() const;

This works as follows:

foo(const SmartPointer& ptr)   {   ptr->bar_method();   }

The above code invokes this method:

Immutable* operator->() const

This, of course, returns an immutable interface. Obviously, an immutable interface will usually not have any methods that will change the state of the object.

On the other hand, the following code:

foo(SmartPointer& ptr)   {   ptr->bar_method2();   }

will invoke:

Mutable* operator->();

This gives you the full power of the mutable interface.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist