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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

technology leadership

Why the World Needs More Technology Leadership

As a fact, technology has touched every single aspect of our lives. And there are some technology giants in today’s world which have been frequently opined to have a strong influence on recent overall technological influence. Moreover, those tech giants have popular technology leaders leading the companies toward achieving greatness.

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job