Search code examples
c++shared-ptr

what is the difference between process(sp) and process(shared_ptr<int>(sp))?


void process(std::shared_ptr<int> ptr) {
  std::cout << "inside the process function:" << ptr.use_count() << "\n";
}

int main() {
  auto sp = std::make_shared<int>();
  process(sp);
  process(std::shared_ptr<int>(sp));
  return 0;
}

Both two outputs are 2, but why?

I think the second output should be 3. Isn't std::shared_ptr(sp) a copy of sp, and isn't the parameter std::shared_ptr ptr in process function another copy of sp?


Solution

  • No, 2 is very much correct.

    std::shared_ptr<int>(sp) is a prvalue. Since C++17, it doesn't even materialize a temporary, rather being used to directly initialized ptr.

    Prior to C++17, that temporary is still elgibile to be used as an argument to a shared_ptr's move constructor. ptr is move constructed from it, and basically takes over the temporarys ownership instead of incrementing the ref-count.