Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

unions

What if I have this:

union{
    vector<int> intVec ;
    vector<float> floatVec ;
    vector<double> doubleVec ;
} ;

Of course, I'll be using just one of the 3 vectors. But... what happens when all the 3 vectors are contructed??
Would the consructors of the 3 vectors interfere with each other?? (since the 3 of them are in the same memory address)

Thanks.

like image 237
GetFree Avatar asked Apr 12 '09 08:04

GetFree


3 Answers

Now C++ standard supports variant. Check https://en.cppreference.com/w/cpp/utility/variant.

std::variant

Defined in header

template <class... Types>   
class variant;

(since C++17)

The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value (this state is hard to achieve, see valueless_by_exception).

As with unions, if a variant holds a value of some object type T, the object representation of T is allocated directly within the object representation of the variant itself. Variant is not allowed to allocate additional (dynamic) memory.

A variant is not permitted to hold references, arrays, or the type void. Empty variants are also ill-formed (std::variant<std::monostate> can be used instead).

A variant is permitted to hold the same type more than once, and to hold differently cv-qualified versions of the same type.

Consistent with the behavior of unions during aggregate initialization, a default-constructed variant holds a value of its first alternative, unless that alternative is not default-constructible (in which case the variant is not default-constructible either). The helper class std::monostate can be used to make such variants default-constructible.

like image 116
harsha Avatar answered Sep 25 '22 14:09

harsha


Current C++ standard does not allow non-POD types inside unions. You will get this compiler error from gcc:

error: member ‘std::vector<int, std::allocator<int> >
<anonymous union>::i’ with constructor not allowed in union
error: member ‘std::vector<int, std::allocator<int> >
<anonymous union>::i’ with destructor not allowed in union

New C++ standard (C++0x) proposes unrestricted unions, but it adds yet more object lifetime pitfalls to C++.

like image 26
Alex B Avatar answered Sep 23 '22 14:09

Alex B


You cannot have unions containing non-POD class types. Your sample will not compile.

You can use boost::variant as a safe alternative to C unions. See the documentation on boost.org. You might, however, reconsider your design and use polymorphism instead. Depends on what you're trying to accomplish, of course.

like image 42
avakar Avatar answered Sep 24 '22 14:09

avakar