Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

placement delete on unrestricted unions

Tags:

c++

c++11

unions

I was reading through the wiki entry for c++11 and I found a section for unrestricted union where you call placement new for the non-trivial memberlink, But the example here did not match that with a delete.

So my question is: do you need a placement delete for unrestricted union? If yes, how? If not, why? Would calling destructor suffice?

example:

class U_t
{
  public:
    union U
    {
        string s;
        U () { new (s) string(); }
    }
    U _data;
    ~U_t () { 
       _data.s.~string();
       //and now what?
    }
}
like image 319
leorex Avatar asked Dec 18 '25 15:12

leorex


1 Answers

§ 9.5/2 If any non-static data member of a union has a non-trivial default constructor, copy constructor, move constructor, copy assignment operator , move assignment operator, or destructor, the corresponding member function of the union must be user-provided or it will be implicitly deleted for the union.

§ 9.5/3 Since std::string declares non-trivial versions of all of the special member functions, [the union] will have an implicitly deleted default constructor, copy/move constructor, copy/move assignment operator, and destructor. To use [the union], some or all of these member functions must be user-provided.

§ 9.5/4 In general, one must use explicit destructor calls and placement new operators to change the active member of a union.

So yes, it requires a destructor call, similar to what you have.

However, to use such a thing safely would be vastly more complex, since you'd have to constantly keep track of what type was active. To safely use a union with non-POD types is really hard. If I were you, only use PODs, or use boost::variant

like image 193
Mooing Duck Avatar answered Dec 21 '25 03:12

Mooing Duck