shared_ptr - pass by value vs pass by reference

后端 未结 3 1130
你的背包
你的背包 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:37

    The EventDispatcher receives an EventPtr and adds it to a queue that gets processed in another thread...but what is an appropriate method signature for the dispatch method?

    Either suggestion is fine; passing by const reference will likely be more efficient, since it won't have to modify the pointer's reference count. In either case, push_back will place a copy of the pointer on the queue, keeping the event alive while it's on the queue.

    Again, what is an appropriate method signature for the process method? I'm wondering if I can just pass the naked Event* to the process method?

    Passing the shared pointer (by value or reference) will clearly document and enforce the ownership of the event, and will allow the processor to keep hold of it after the call to process() if it needs to. Passing a raw pointer introduces uncertainty into the ownership; the processor will need a contract stating that it isn't taking ownership of the event, and must not attempt to access it once process() has ended.

提交回复
热议问题