Actual Aim
: Delete/Destroy the network from the vector and reintroduce it if needed.
So I wrote a small program to try the same.
I am facing problems in delete
ing a shared pointer and setting it to nullptr
. Directly setting to nullptr
will lead to dangling pointer. How can I free that position without causing a memory leak?
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class ptr{
public:
int x;
ptr(int a):x(a){ }
~ptr()
{
cout << "destructor\n";
}
};
int main()
{
std::vector<shared_ptr<ptr>>v;
v.push_back(shared_ptr<ptr>(new ptr(100)));
v.push_back(shared_ptr<ptr>(new ptr(200)));
v.push_back(shared_ptr<ptr>(new ptr(300)));
v.push_back(shared_ptr<ptr>(new ptr(400)));
v.push_back(shared_ptr<ptr>(new ptr(500)));
auto it = v.begin();
int i = 0;
while(i < 5)
{
if((*it)->x == 300)
{
cout << "300 found \n";
delete (*it); // -> Problem is here.
}
it++;
i++;
}
return 0;
}