Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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.

Vijai Kalyan
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap