best practice when returning smart pointers

前端 未结 9 1449
一生所求
一生所求 2020-12-24 11:56

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 co

9条回答
  •  抹茶落季
    2020-12-24 12:16

    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.

提交回复
热议问题