The code below causes a runtime error.
Each shared_ptrstores the same memory, but still the counter for each of them is one.
So, each generic pointer is different, so when they go out of scope, they try to free the block, and this causes the heap to corrupt. My question is: how to avoid this?
I just want to add an ad like this
shared_ptr<int> x(p);
not 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;
}
source
share