shared_ptr - pass by value vs pass by reference

后端 未结 3 1120
你的背包
你的背包 2021-02-15 14:05

Suppose I have:

typedef boost::shared_ptr EventPtr;

On one thread, I am creating an Event and sending it off to get d

3条回答
  •  伪装坚强ぢ
    2021-02-15 14:50

    In the big picture, it doesn't matter too much whether you pass by value or by reference. Either way, the reference count will be increased when you copy the shared_ptr to push it onto the queue.

    Passing the naked pointer is okay too as long as you're careful you don't end up with two different shared_ptr instances with different reference counts, one in the caller and one in the callee.

    Personally, I like the pass-by-value option because it feels more like passing a real pointer around. Requiring a shared_ptr as an argument also reminds the programmers calling the function that it wants the lifetime of the object to exceed the function call and that the caller may want to store the argument in a shared_ptr anyway in case the function returns early if an exception is thrown, etc.

提交回复
热议问题