c++ - shared pointer assertion fail after iteration in a loop -


i new shared_ptr boost , considering iterate on set best object. edit: added information first_world

std::set<world::cptr> first_world = ... // long call, gets set of constant shared pointers class world, various methods exist     typedef boost::shared_ptr<world const> cptr;    world::cptr best = *(first_world.begin());    (world::cptr lo : first_world) {      if (best->getvalue() >= lo->getvalue() ){        best = lo;      }    } 

later want use shared pointer, program crashes communicate assertion `px != 0' failed. followed rules here, mean used shared pointer iterator in loop assign pointer. bad practice, there better practice?

cout << "name is: " << best->getdefinition() << endl; 

nothing's blatantly wrong in what's pasted there, there's going mistake in long call creates set.

for example, easy mess if raw pointers involved when adding elements set. consider situation, concrete illustration of common mistake that's sort of alluded in best practices link:

std::set<world::cptr> first_world;  world* pworld = new world();  // bad: first_world.insert(world::cptr(pworld)); first_world.insert(world::cptr(pworld));  // oops!! have 2 independently refcounted entries in first_world!  // emplace deadly, more subtle. // you'll have 3 shared pointers in set: first_world.emplace(pworld); 

if through entries in first_world , see duplicates you'll know you're in trouble. avoid mistakes this, make sure construct shared_ptrs other shared_ptrs (or boost::make_shared).

so that's tip #1: avoid constructing shared_ptrs raw pointers. (that includes this pointer if worlds adding set... if you're doing that, better start googling enable_shared_from_this).

now let's follow guideline expected behavior:

std::set<world::cptr> first_world;  world::cptr spworld1 = boost::make_shared<world>(); world::cptr spworld2{spworld1};  first_world.insert(spworld1); first_world.insert(spworld2); // 1 element in first_world now, expected. 

finally, few (somewhat unrelated) suggestions:

  • std::set you've declared looking @ address of world objects on heap when compares entries. if have 2 different worlds on heap logically identical they'll both have distinct entries in set. intent? you'll need plug in own custom compare function (std::set's second template argument) deep comparison of worlds if want avoid logical duplicates.
  • check make sure first_world isn't empty before looking max, otherwise bad things happen.
  • standard algorithms friend! consider using std::max_element algorithm instead of raw loop. (this makes easier other people reason you're doing quick glance).

Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -