Is it possible to put several objects together inside a union?

后端 未结 6 1928
无人及你
无人及你 2021-02-08 06:38

What if I have this:

union{
    vector intVec ;
    vector floatVec ;
    vector doubleVec ;
} ;

Of cours

6条回答
  •  情书的邮戳
    2021-02-08 07:00

    Would the consructors of the 3 vectors interfere with each other?? (since the 3 of them are in the same memory address)

    The C++ standard doesn't allow your program, so it's (at best!) implementation-defined what happens.

    If, say, your implementation invokes all three default contructors, and those all alocate memory, and stores the pointer to the newly allocated space, the you have a memory leak (the first Two allocations are overwritten by the third).

    If the destructors are all invoked and they all free "their" memory, you will be doing a double free (triple, acually); this is likely to corrupt the allocation data structure, which is a Bad Thing. Be happy if you crash, because it's much harder to debug if you don't.

    I think these problems might be why the standard doesn't allow this.

    (A more sensical thing might be to only default-construct the first class, but that's still not sensical, just less insane...)

提交回复
热议问题