Alex Rivera | Logout

best practice when returning smart pointers

Asked 2009-06-10T11:12:33.817
33

What is the best practice when returning a smart pointer, for example a boost::shared_ptr? Should I by standard return the smart pointer, or the underlying raw pointer? I come from C# so I tend to always return smart pointers, because it feels right. Like this (skipping const-correctness for shorter code):

class X
{
public:
    boost::shared_ptr<Y> getInternal() {return m_internal;}

private:
    boost::shared_ptr<Y> m_internal;
}

However I've seen some experienced coders returning the raw pointer, and putting the raw pointers in vectors. What is the right way to do it?

Edit
Report

2 Answers

0

depends on your goals.

blindly returning smart ptr to internal data might not be a good idea (which is very sensitive to the task you're trying to solve) - you might be better off just offering some doX() and doY() that use the pointer internally instead.

on the other hand, if returning the smart ptr, you should also consider that you'll create no mutual circular references when objects end up unable to destroy each other (weak_ptr might be a better option in that case).

otherwise, like already mentioned above, performance/legacy code/lifetime considerations should all be taken into account.

answered 2009-06-10T11:22:21.473
-2

const boost::shared_ptr &getInternal() {return m_internal;}

This avoids a copy.

Sometimes you'll like to return a reference, for example:

  • Y &operator*() { return *m_internal; }
  • const Y &operator*() const { return *m_internal; }

This is good too only if the reference will be used and discarded inmediately. The same goes for a raw pointer. Returning a weak_ptr is also an option.

The 4 are good depending on the goals. This question requires a more extensive discussion.

answered 2009-06-11T13:36:58.733

Your Answer