c++ pass default shared_ptr reference as nullptr

First of all, shared_ptr can be a nullptr.  Nothing wrong passing a null shared pointer.

In fact, a null shared pointer is an actual Null Object, which means that it’s designed exactly for those kinds of uses.

 

but if we want to pass the share_ptr as default nullptr reference, we need to put a const before that

Example is better than words, here is an example how to pass shared

 

#include <memory>
#include <iostream>

class A
{

public:
// OK,  for reference we need const
A( const std::shared_ptr<std::string>& t = nullptr ) : my_shared(t){}
// ERROR , will have compile error
// A( std::shared_ptr<std::string>& t = nullptr ) : my_shared(t){}

// pass by value works without const
// A( std::shared_ptr<std::string> t = nullptr ) : my_shared(t){ }

void output() {
if(my_shared) {
std::cout << my_shared->c_str() << std::endl;
} else {
std::cout <<” null prt” << std::endl;
}
}

private:
std::shared_ptr<std::string> my_shared;

};
int main()
{

std::shared_ptr<std::string> t = nullptr;

A a( t );
a.output();

A a2( nullptr );
a2.output();
std::shared_ptr<std::string> t2 = std::make_shared<std::string>(“test shared”);

A b(t2);
b.output();

}

 

C++ said  we can bind the value of a temporary expression to a constant reference,

and the lifetime of the expression is extended to that of the reference.

But we cannot do this with a non-constant (lvalue) reference.

 

string& s3       = string("s3"); // ERROR! non-const reference not allowed!


References

https://stackoverflow.com/questions/14612933/const-reference-default-value


https://stackoverflow.com/questions/25920681/what-is-the-difference-between-an-empty-and-a-null-stdshared-ptr-in-c

Please rate this


Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>