Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference counting not working in shared_ptr

The below code results in run time error.

Each shared_ptr holds the same memory, but still the count for each one is one.

So, each shared pointer is different, so when they go out of scope they try to free the block and this causes corrupting the heap. My question is how to avoid this?

Just want to add declaration like this

shared_ptr<int> x(p);

is non negotiable I have to declare it.

#include <iostream>
#include <memory>
using namespace std;
int main ()
{
  int* p = new int (10);
  shared_ptr<int> a (p);
  shared_ptr<int> b (p);
  shared_ptr<int> c (p);
  shared_ptr<int> d (p);
  cout<<"Count : "<<a.use_count()<<endl;
  cout<<"Count : "<<b.use_count()<<endl;
  cout<<"Count : "<<c.use_count()<<endl;
  cout<<"Count : "<<d.use_count()<<endl;
  return 0;
}
like image 882
user3798283 Avatar asked Dec 24 '22 07:12

user3798283


1 Answers

You may only crate a smart pointer from a raw one if you have ownership over the pointer. As soon as you create the smart pointer, the ownership will have been passed to the smart pointer. Since you no longer have the ownership, you may not create additional smart pointers from the raw pointer.

To get a shared pointer to memory that is already managed/owned by a shared pointer, you must copy from the existing shared pointer:

shared_ptr<int> b = a;
shared_ptr<int> c = a;
// ....

If you simply create multiple shared pointers from the raw pointer, then none of those shared pointers will know about the existence of each other, and all of them will believe to be the sole owner of that memory and the problems you describe will occur.

like image 163
eerorika Avatar answered Jan 04 '23 23:01

eerorika