I wrtoe this code to store objects on the heap. Works fine... but I wonder about the "need" or perhaps better said any benefit to writing code like this. Wouldn't STL data structures like deque already do what I wrote here automatically, that is to say, store the objects on the heap?
In case it isn't clear, the sytax I used data.push_back( shared_ptr(new Vehicle("aba")) ); makes it store objects on heap, but wouldn't data.push_back( Vehicle("aba") ); do the same by default?
then I could pass to functions a reference to the data structure and it would be equally lean either way, no? At this point I;m questioning whether there is really any use case for bothering with smart pointers when the objects stored are stored in a an STL data structure. Perhaps I should just let C++ auto manage this and then pass around smart pointers to the data structure itself, or just a reference to it.
deque<shared_ptr<Vehicle>> data;
data.push_back( shared_ptr<Vehicle>(new Vehicle("aba")) );
data.push_back( shared_ptr<Vehicle>(new Vehicle("bobo")) );
data.push_back( shared_ptr<Vehicle>(new Vehicle("cici")) );
data.push_back( shared_ptr<Vehicle>(new Vehicle("dede")) );
data.push_back( shared_ptr<Vehicle>(new Vehicle("efee")) );
for(unsigned int i =0; i < data.size(); i++ )
{
cout << data.at(i)->getName() << endl;
}
data.pop_front();
data.pop_back();
for(deque<shared_ptr<Vehicle>>::iterator i = data.begin(); i != data.end(); )
{
cout << (*i)->getName() << endl;
++i;
}
Aucun commentaire:
Enregistrer un commentaire