c++ - Memory leaks when using shared pointers in a vector -
c++ - Memory leaks when using shared pointers in a vector -
i've been facing problem memory leaks when adding shared pointer vector, vector defined follows:
vector<shared_ptr<recipe>> favorites;
(recipe simple class 2 simple fields)
and next function used add together recipe user's favorites:
void user::postrecipe(string recipename) { if (!(*this).isconnected()) throw usernotconnectedexception(); if (!(*this).isingroup()) throw notingroupexception(); shared_ptr<user> owner = server->seekuser((*this).getid()); shared_ptr<recipe> recipe(new recipe(recipename, owner)); server->postrecipe((*this).groupname, recipe); if (!checkifrecipeinfavs(favorites, recipename)) { favorites.push_back(recipe); }
although programme compiles , output of programme desired, lastly line of functions seems cause memory leak , error disappears if removed.
any ideas? in advance.
recipe.h:
class recipe { string name; shared_ptr<user> owner; public: recipe(string name, shared_ptr<user> owner):name(name),owner(owner){}; ~recipe(){}; string getname(); shared_ptr<user> getowner(); };
recipe.cpp:
string recipe::getname(){ homecoming name; } shared_ptr<user> recipe::getowner(){ homecoming owner; }
when store owner in recipe using shared pointer, create cyclic reference, meaning, recipe deleted when user deleted, user deleted when recipes deleted. should utilize weak_ptr
in recipe break cycle.
this because shared_ptr
uses simple reference counting determine when should delete pointee: whenever re-create shared_ptr
, reference count (kept on heap, alongside pointee object) incrementented, , whenever re-create gets destroyed, count decremented. pointer sees count reach 0 in destructor delete object. when 2 shared_ptr
s reference each other, count never fall below two.
c++ vector memory-leaks shared-ptr
Comments
Post a Comment