C++中用dynamic_cast实现downcast之一见

来源:互联网 发布:厦门智业软件 编辑:程序博客网 时间:2024/04/29 10:58
Almost   alway   it   will   be   on   the   right   track   if   we   use   "dynamic_cast "   for   up-casting,   with   either   a   pointer   or   a   reference,   to   a   type   of   sub-class   from   that   of   base-class,   and   this   would   be   guaranteed   to   be   safe   in   most   cases.   Nevertheless   possibly,   if   you   ever   deploy   it   by   yourself,   it   will   not   act   as   you   expect   if   you   use   this   casting   operator   for   down-casting   instead.   For   me,   not   so   that   lucky   it   is!

  Now   let 's   show   you   the   scenario   as   this:   Originally   I   dynamically   create   an   object   of   the   sub-class   and   assign   the   returned   pointer   to   a   pointer   to   the   base-class,   then   actually   I   just   intend   to   cast   this   pointer   to   base-class   back   to   pointer   to   the   sub-class,   which   seems   absolutely   reasonable   and   nothing   unpredictable   would   be   expected,   but   thing   only   to   run   out   of   its   normal   way!

  Passing   through   the   compilation   is   entirely   ok,   but   when   I   trigger   the   program,   an   run-time   error   bursts   out,   which   is   concerning   such   and   such   a   memory   allocation   on   the   heap.   Then   I   try   the   same   case   for   downcasting   a   reference   instead   of   pointer,   the   result   stands   the   same,   in   the   end   ,therefore,   I   am   buffled!

  After   nearly   a   week   of   being   bewildered   and   puzzled,   edificed   by   a   post   issued   from   a   fellow   CSDNer,   I   recall   a   critical   try   --   the   compilation   option   that   controls   the   support   for   RTTI.   Woo!   I   cry,   doesn 't   the   dynamic-cast   depend   on   the   sustenance   of   RTTI   by   the   run-time   system?  
   
  Definitely   that 's   the   key   I 've   been   dredging   toiling   to   search!   Immediately   after   I   open   the   option   in   the   compilation   configuration,   everything   goes   extremely   right! 
 
原创粉丝点击