Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I gather unrestricted unions as one of the functionality being put forth in C++11. Can anyone please explain the semantics behind this and the advantages it provides?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
400 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is an explaination on Wikipedia : http://en.wikipedia.org/wiki/C%2B%2B0x#Unrestricted_unions

Search there first before asking about C++0x features explainations.

Unrestricted unions

In Standard C++ there are restrictions on what types of objects can be members of a union. For example, unions cannot contain any objects that define a non-trivial constructor. C++0x will alleviate some of these restrictions, allowing unions to be used on more types that they were previously not allowed to be used on.[6] This is a simple example of a union permitted in C++0x:

//for placement new
#include <new>

struct Point  {
    Point() {}
    Point(int x, int y): x_(x), y_(y) {}
    int x_, y_;
};
union U {
    int z;
    double w;
    Point p;  // Illegal in C++; point has a non-trivial constructor. 
              //   However, this is legal in C++0x.
    U() { new( &p ) Point(); } // No nontrivial member functions are
                               //implicitly defined for a union;
                               // if required they are instead deleted
                               // to force a manual definition.
};

The changes will not break any existing code since they only relax current rules.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...