I'm currently working on new project with my team in Cpp and we decide to say good bye to the old fashioned raw pointers and give the smart pointers a try.
I'm really new at this world and decided to try a few things that I'll need for our project before use them for real.
The thing is, I started with the basics, and then I've got stucked with this.
When I create two new (shared) pointers (see the code below) with the make_shared function, and then (cross) store them in the other's inner vector, neither of them get destroyed at the end of the program.
shared_ptr.cpp:
#include <iostream>
#include <memory>
#include <vector>
#include <string>
using namespace std;
class Object{
public:
vector<shared_ptr<Object>> list;
string name;
Object(string name){
this->name=name;
}
~Object(){
cout<<"...Deleting "<<name<<endl;
}
};
int main(){
shared_ptr<Object> o1 = make_shared<Object>("o1");
shared_ptr<Object> o2 = make_shared<Object>("o2");
o1->list.push_back(shared_ptr<Object>(o2));
o2->list.push_back(shared_ptr<Object>(o1));
}
compiler instructions
g++ shared_ptr.cpp -o shared.o && ./shared.o
My question here is, shouldn't the shared pointer handle the reference itself? Or should I be the one to clear the inside-vector before the program finished?
Maybe I just have to store raw pointers in the inner lists and just stick to the smart pointers in those sections where I do create and delete them.
I have to use a similar structure in my project, that's why I wanted to ask here first before frustrating and going back to the old (but effective) raw pointer.
Thanks!
Object
and "disconnect" them? β David Schwartz