Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An union with a const and a nonconst member?

Tags:

This appears to be undefined behavior

union A {   int const x;   float y; };  A a = { 0 }; a.y = 1; 

The spec says

Creating a new object at the storage location that a const object with static, thread, or automatic storage duration occupies or, at the storage location that such a const object used to occupy before its lifetime ended results in undefined behavior.

But no compiler warns me while it's an easy to diagnose mistake. Am I misinterpreting the wording?

like image 608
Johannes Schaub - litb Avatar asked Apr 13 '11 17:04

Johannes Schaub - litb


People also ask

Can a c++ union have a constructor?

A union can have member functions (including constructors and destructors), but not virtual functions. A union cannot have base classes and cannot be used as a base class. A union cannot have non-static data members of reference types.

What is the union type in c++?

In C++17 and later, the std::variant class is a type-safe alternative for a union. A union is a user-defined type in which all members share the same memory location. This definition means that at any given time, a union can contain no more than one object from its list of members.

How to declare union in c++?

union { int no; char name[20], float price; }; In this, the size of the member, name is more than the size of other members (sr, price) so the size of a union in memory (char × 20 = 20 byte) will be 20 bytes.


1 Answers

The latest C++0x draft standard is explicit about this:

In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.

So your statement

a.y = 1; 

is fine, because it changes the active member from x to y. If you subsequently referenced a.x as an rvalue, the behaviour would be undefined:

cout << a.x << endl ; // Undefined! 

Your quote from the spec is not relevant here, because you are not creating any new object.

like image 107
TonyK Avatar answered Oct 13 '22 19:10

TonyK