C++ - passing references to std::shared_ptr or boost::shared_ptr

前端 未结 17 1655
日久生厌
日久生厌 2020-11-28 01:20

If I have a function that needs to work with a shared_ptr, wouldn\'t it be more efficient to pass it a reference to it (so to avoid copying the shared_ptr

17条回答
  •  清酒与你
    2020-11-28 02:02

    struct A {
      shared_ptr msg;
      shared_ptr * ptr_msg;
    }
    
    1. pass by value:

      void set(shared_ptr msg) {
        this->msg = msg; /// create a new shared_ptr, reference count will be added;
      } /// out of method, new created shared_ptr will be deleted, of course, reference count also be reduced;
      
    2. pass by reference:

      void set(shared_ptr& msg) {
       this->msg = msg; /// reference count will be added, because reference is just an alias.
       }
      
    3. pass by pointer:

      void set(shared_ptr* msg) {
        this->ptr_msg = msg; /// reference count will not be added;
      }
      

提交回复
热议问题