Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Oct 12, 2005



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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->();

Immutable* operator->() const;
This works as follows:

foo(const SmartPointer& ptr)
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)
will invoke:

Mutable* operator->();
This gives you the full power of the mutable interface.

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