On deleting C++ pointers -


ok..so confuses hell out of me. dealing legacy c++ code parts of have feeling not safe, not 100% sure. here's snippet, example of risky stuff.

struct {     a() : a_ptr(0) {}     a(some_type *ptr) : a_ptr(ptr) {}     const some_type *a_ptr; };  struct b {     b() : b_ptr(0) {}     b(some_type *ptr) : b_ptr(ptr) {}     const some_type *b_ptr; };  struct data {     data(...) {//-stuff doesn't invole aptr_list or bptr_list;     }     ~data() {         for(std::vector<a*>::iterator itr = aptr_list.begin(); itr != aptr_list.end() ++itr) {             delete *itr;         }         for(std::vector<b*>::iterator itr = bptr_list.begin(); itr != bptr_list.end() ++itr) {             delete *itr;         }     }     std::vector<a*> aptr_list;     std::vector<b*> bptr_list; private:     data(const data&);     data& operator=(const data&); }; 

then in implementation, find:

void some_func(...) {     //-inside function     data& d = get_data(...);     ...     for(...) {          some_type *sptr = dynamic_cast<some_type*>(a_source_of_some_type_pointer);          a* = new a(sptr);          b* b = new b(sptr);          d.aptr_list.push_back(a);          d.bptr_list.push_back(b);     } } 

i little uneasy same pointer sptr being used in implementation above; create problems when destructor of data invoked? on other hand, looks have 2 new calls a* , b* , 2 deletes, if destructor in data not deep - , maybe that's need clarification, perhaps safe after , concern misplaced? did notice structs a , b instance don't have destructors defined, hope not deep. not sure if means pointer data freed or not. appreciate expert insights always.

thanks time , interest.

a , b not have user defined destructor, nothing inside a or b gets destroyed (other actual memory holds being freed up, since sptr held there, not being deleted). [obviously, if a or b contains other class, std::string or std::vector, class destroyed].

so, in other words, code fine - a , b holds copy of sptr, it's never deleted [in bit of code, if needs deleting later, that's different matter].


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -