c++ - VS 2013 exception when using C++11 unrestricted unions -
consider code:
struct tnumeric { bool negative; wstring integral; wstring fraction; }; union tvalue { // unnamed structs needed because otherwise compiler not accept it... bool bit; struct{ tnumeric numeric; }; struct{ wstring text; }; }; tnumeric numeric; tnumeric &rnumeric{ numeric }; rnumeric.integral = l""; rnumeric.integral.push_back( l'x' ); //ok, no problem tvalue value; tvalue &rvalue{ value }; rvalue.text = l""; rvalue.text.push_back( l'x' ); //ok, no problem rvalue.numeric.integral = l""; rvalue.numeric.integral.push_back( l'x' ); // exception
in release mode there no problem. when run in debug mode there exception @ last statement in method _adopt of class _iterator_base12 in xutility: access violation reading location 0x0000005c
.
in _adopt code run when _iterator_debug_level == 2
. tried with
#define _iterator_debug_level 1
added in main program remains defined 2. there way disable check?
vs 2013 doesn't support c++11 unrestricted unions, implements unions per c++03:
an object of class non-trivial constructor (12.1), non-trivial copy constructor (12.8), non-trivial destructor (12.4), or non-trivial copy assignment operator (13.5.3, 12.8) cannot member of union
you fooled compiler using unnamed structs, doesn't solve problem: objects non-trivial, , vs2013 doesn't support that.
when switch more c++11-compliant compiler, such vs 2015, you'll have implement constructor, destructor, copy constructor etc. union in way safely constructs/destructs/copies appropriate part of union. there's example in standard (i'm quoting c++14 draft n4140 [class.union]/4):
consider object
u
of union typeu
having non-static data membersm
of typem
,n
of typen
. ifm
has non-trivial destructor ,n
has non-trivial constructor (for instance, if declare or inherit virtual functions), active member ofu
can safely switchedm
n
using destructor , placement new operator follows:u.m.~m(); new (&u.n) n;
Comments
Post a Comment