c++ - How to get data without corruption when void* is used? -


well, using map store kind of pointer (void*), , being used in scope object. here scope class.

class scope {   protected:     scope * parent;     mymap* map;   public:     virtual void setparent(scope* p)=0;     virtual scope* getparent()=0;     virtual void setowner(void * owner)=0;     virtual void * getowner()=0;     virtual symbol * get(char* name)=0;     virtual symbol * get(char* name, signature * sig)=0;     mymap* getmap()const;  }; 

and there 2 classes orderedscope , disorderedscope implement scope class.

in project i'm trying store data void* , retrieve them , cast them apropriate type. when cast object on type, found data lost. here photo of got. enter image description here

just clarify package class has scope. , in scope storing objects of type functions. when want add function should retrieve package object first can use add function insert new function.

i don't know if showed problem correctly, hope so. appreciated.

void pointers risky mechanism, disable compiler's type-checking pointer. therefore if make mistake (such casting void pointer wrong type), won't compile-time error, notice problem run-time misbehavior, such data corruption.

so, answer question: if want use void pointers , avoid data corruption, have make very sure when cast void-pointer (sometype *), memory location void-pointer points in fact contain valid (sometype *) , nothing else. in particular, have make sure (sometype *) void pointer pointing still valid, , hasn't been deleted/freed between time created void-pointer , time attempting cast , use it. need aware of potential gotchas involved when combining void pointers multiple inheritance, class multiple superclasses can have different "this" pointer depending on superclass viewing as, , casting void-pointer won't automatically store correct "this" pointer (since compiler can't know "this" pointer you're going interested in later).

this doable, program's logic has 100% correct in cases. there's no shortcut other code carefully, study code looking errors, , test thoroughly. code-checkers valgrind , purify can helpful in finding errors symptoms aren't obvious running code.

that said, commenters above right -- there better/safer alternatives using void-pointers. these alternatives (such templates and/or common base class) less error-prone, because let compiler detect errors @ compile-time rather forcing hunt them down 1 one @ run-time. also, consider using smart pointers (e.g. shared_ptr) rather raw pointers, offload handling object lifetimes compiler, can handle task more reliably , consistently hand-rolled code can.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -