shared_ptr - pass by value vs pass by reference

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

    Both dispatch functions will work properly.

    In the first case, an instance of shared pointer will be copied on the stack and then copied again when adding to the event queue. This means copying of the pointer and increase of reference counter.

    dispatch(EventPtr event);  //will push_back(event)
    

    In the second case just a reference to an existing instance will be passed to the function and then copied into the queue. I'd use this variant.

    dispatch(const EventPtr& event);  //will push_back(event);
    

    When passing the shared pointer to process(), you can also pass it by reference:

    class EventProcessor {
        process(const EventPtr& event);
    }
    

提交回复
热议问题