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++