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;
}
Its a little odd that you are using smart pointers and at the same time want to manually manage the memory.
However, there are several ways to let a smart pointer release the managed object:
reset()
, effectively the same as...shared_ptr<int>().swap(v[i])
None of that results in a leak or a dangling pointer. You can misuse shared_ptr
to create a dangling pointer or to get a memory leak, but you would have to really push hard to do so.
Actual Aim: Delete/Destroy the network from the vector and reintroduce it if needed.
This doesn't sound like smart pointers but rather like std::vector<std::optional<ptr>>
. Alternatively consider to use a std::unordered_map<int,ptr>
which can model a sparse std::vector
where you can erase elements while the others keep their key (=index).