Vector of structs c++ -
i having issue creating vector of structs. in function addapp unable "push_back" newly allocated struct vector. error message "invalid arguments". looked around see if had similar issue nothing helped. can point out whats flaw in logic? thx.
class appholder { private: struct info { int refnumber; string name; string link; }; vector<info> database; public: void addapp(int ,string ,string ); }; void appholder::addapp(int r, string n, string l) { info *newapp = new info; newapp -> name = n; newapp -> link = l; newapp -> refnumber = r; database.push_back(newapp); }
the reason code fails std::vector<info>::push_back
requires pass object of type info
, pass info*
.
we can solve using info
objects directly instead of using pointers new
ed variables:
void appholder::addapp(int r, string n, string l) { info newapp; newapp.name = n; newapp.link = l; newapp.refnumber = r; database.push_back(newapp); }
info* newapp = new info;
declares pointer info, , initializing address of dynamically created object of type info
, must deleted later, or destructor won't called , memory won't released.
info newapp;
declares automatic variable of type info
destructor called @ end of scope, , memory released.
using new
pointers discouraged in modern c++, requires manual delete
of pointers, it's exception-unsafe (if exception thrown before delete, resources aren't deleted) , involves writing lot of code (copy constructor, copy assignment operator, destructor, move constructor, move assignment operator) ensure class works correctly. there are, however, situations pointer usage required (storing instances of derived classes in containers), in case want use smart pointers can manage resources you.
Comments
Post a Comment