Std :: weak_ptr assignment with std :: make_shared

I came across this behavior while using std::weak_ptr

and std::make_shared

, and I found it a little strange. I am using C ++ 11.

#include <iostream>
#include <memory>

int main()
{
  std::weak_ptr<int> weak;

  std::shared_ptr<int> shared {std::make_shared<int>(42)};
  weak = shared;
  std::cout << "Meaning of life: " << *weak.lock() << std::endl;

  weak = std::make_shared<int>(23);
  std::cout << "Meaning of life: " << *weak.lock() << std::endl;

  return 0;
}

      

The first one std::cout

prints fine, the second one gives me a segfault. I've tried looking at the pages std::weak_ptr

and std::shared_ptr

at cppreference , but I still don't understand why this is happening. Creating a temporary object seems cumbersome to me, is this something that was covered in C ++ 14 or is there something I can't see?

Thank!

+3


source to share


2 answers


weak_ptr

can only be dereferenced after blocking, if the object shared_ptr

still exists pointing to the same underlying object.

In the first part

std::shared_ptr<int> shared {std::make_shared<int>(42)};
weak = shared;
std::cout << "Meaning of life: " << *weak.lock() << std::endl;

      

It really is. In the second part



weak = std::make_shared<int>(23);
std::cout << "Meaning of life: " << *weak.lock() << std::endl;

      

it is not, because it shared_ptr

was a temporary object.

What you are running into is exactly what it was created for weak_ptr

- that it is only valid as long as some others shared_ptr

point to the same underlying object. This is its purpose :

std :: weak_ptr is a smart pointer that contains a reference to an unowned ("weak") object reference that is controlled by std :: shared_ptr ... If the original std :: shared_ptr is destroyed at this time, the lifetime of the object is extended to until the temporary std :: shared_ptr is destroyed.

+5


source


This is because you create a temporary shared pointer and immediately assign it to a weak pointer on this line:

weak = std::make_shared<int>(23);

      



After the assignment completes, the temporary shared pointer is destroyed, the reference count reaches 0 (since weak pointers do not increment the reference count), and therefore the resource on the heap is discarded.

+2


source







All Articles