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

// 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;

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

int main()

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

A a( t );

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

A b(t2);



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!




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>