Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ rvalue shared_ptr and rvalue weak_ptr

std::shared_ptr<std::string> test() {
  return std::make_shared<std::string>("sdsd");
}
cout << *test() << endl;

The above code works. Can someone please let me know where is the "sdsd" string stored. I was expecting it to error out as rvalue is a temporary object. Where is the rvalue copied to and stored in?

With weak_ptr

std::weak_ptr<std::string> test() {
  return std::make_shared<std::string>("sdsd");
}
  cout << *test().lock() << endl;

Interestingly the above code errors out. What’s the difference?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In

std::shared_ptr<std::string> test() {
  return std::make_shared<std::string>("sdsd");
}

the constructed shared_ptr is returned and lives on as a temporary variable long enough to be used by the caller before going out of scope and freeing the string allocated by make_shared.

The "sdsd" string is stored in dynamic storage owned by the returned shared_ptr.

In

std::weak_ptr<std::string> test() {
  return std::make_shared<std::string>("sdsd");
} 

the shared_ptr wasn’t returned and went out of scope, taking the string allocated by make_shared with it. Since this was the only existing copy of the shared_ptr this leaves the returned temporaty weak_ptr variable connected to an expired share_ptr. If you test the return value of lock you’ll see it’s a default-constructed shared_ptr holding a null pointer.

Documentation for std::weak_ptr::lock.

The "sdsd" string isn’t stored anywhere after test returns. It departed when the shared_ptr that owned it went out of scope.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading