Can a smart pointer passed by reference be a nullptr?

Viewed 339

There are many questions about passing smart pointers by reference. What I did not find is a definite answer on: Can we pass a nullptr to a method accepting a smart pointer by reference?

Example:

void myFunc(std::shared_ptr<std::string> &myStrRef) {
   // do something
}

void main() {
   myFunc(nullptr);
}
1 Answers

Can we pass a nullptr to a method accepting a smart pointer by reference?

Not with a non-const lvalue reference.

void myFunc(std::shared_ptr<std::string> &myStrRef) {
   // do something
}

void main() {
   myFunc(nullptr);
}

Will fail to compile because myStrRef can't be bound to a temporary object. If you instead had

void myFunc(const std::shared_ptr<std::string> &myStrRef) {
   // do something
}
// or
void myFunc(std::shared_ptr<std::string> &&myStrRef) {
   // do something
}

Then it would be legal because those references can bind to a temporary object.

Related