How to get the Object being pointed by a shared pointer?

Pavan Dittakavi picture Pavan Dittakavi · Jun 27, 2011 · Viewed 48.9k times · Source

I have a query. Can we get the object that a shared pointer points to directly? Or should we get the underlying RAW pointer through get() call and then access the corresponding object?

Answer

Ken Wayne VanderLinde picture Ken Wayne VanderLinde · Jun 27, 2011

You have two options to retrieve a reference to the object pointed to by a shared_ptr. Suppose you have a shared_ptr variable named ptr. You can get the reference either by using *ptr or *ptr.get(). These two should be equivalent, but the first would be preferred.

The reason for this is that you're really attempting to mimic the dereference operation of a raw pointer. The expression *ptr reads "Get me the data pointed to by ptr", whereas the expression *ptr.get() "Get me the data pointed to by the raw pointer which is wrapped inside ptr". Clearly, the first describes your intention much more clearly.

Another reason is that shared_ptr::get() is intended to be used in a scenario where you actually need access to the raw pointer. In your case, you don't need it, so don't ask for it. Just skip the whole raw pointer thing and continue living in your safer shared_ptr world.