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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With