Smart Pointers and std::unique_ptr

Should I Pass Smart Pointers by Reference?

Should I pass smart pointers by value or reference?

Illustration representing computer hardware

In general, it's recommended to pass smart pointers by value.

Passing by value allows the function to take ownership of the pointer if needed (using std::move), or to simply use the pointer without affecting ownership.

#include <memory>
#include <iostream>

void UseResource(std::unique_ptr<int> Resource) {
  std::cout << *Resource << '\n';
  // Function ends, Resource is destroyed
}

int main() {
  auto Resource{std::make_unique<int>(42)};
  UseResource(std::move(Resource));
}
42

Passing by reference is typically used when you want to modify the smart pointer itself, not just the resource it points to.

For example, you might use a reference if you want the function to be able to reset the pointer:

#include <memory>
#include <iostream>

void ResetResource(std::unique_ptr<
  int>& Resource) {
  Resource.reset(new int{24});
}

int main() {
  auto Resource{std::make_unique<int>(42)};
  std::cout << *Resource << '\n';
  ResetResource(Resource);
  std::cout << *Resource << '\n';
}
42
24

However, these situations are less common. Most of the time, passing by value is sufficient and clearer.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved