Should I Pass Smart Pointers by Reference?

Should I pass smart pointers by value or reference?

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.

Smart Pointers and std::unique_ptr

An introduction to memory ownership using smart pointers and std::unique_ptr in C++

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Mixing Smart and Raw Pointers
Is it okay to mix smart pointers and raw pointers in the same program?
Dynamically Allocating Arrays with Smart Pointers
How do I dynamically allocate an array with smart pointers?
Using Smart Pointers with Custom Deleters
Can I use smart pointers with my own custom deleters?
std::make_unique vs new Keyword
What are the advantages of using std::make_unique over the new keyword?
Using std::move with std::unique_ptr
What does std::move do when used with std::unique_ptr?
Using std::unique_ptr as a Class Member
How do I use std::unique_ptr as a member of a class?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant