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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With