c++ - When a boost::shared_ptr might not be freed? -


afer reading topic c++ interview preparation (matt's answer) i've got question boost::shared_ptr. possible shared_ptr leak memory? how?

shared_ptr uses reference counts, , means circular references can cause leaks. concretely:

struct {     shared_ptr<a> other; };  shared_ptr<a> foo() {     shared_ptr<a> one(new a);     shared_ptr<a> two(new a);     one->other = two;     two->other = one;     return one; } 

the data structure returned foo never deallocated without manual intervention (set either of other pointers null).

now fact every programmer should know; more interesting interview conversation it. options include:

  • redesigning data structure pointer cycles not necessary;
  • demoting @ least 1 pointer in every cycle non-owning reference (a bare pointer or weak_ptr);
  • a dedicated cycle collector;
  • as last resort, manually nulling out pointers @ appropriate points (this breaks exception safety).

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -