Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a smart pointer passed by reference be a nullptr?

Tags:

c++

c++11

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);
}
like image 276
benjist Avatar asked Mar 25 '26 03:03

benjist


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.

like image 157
NathanOliver Avatar answered Mar 26 '26 17:03

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!