samedi 22 avril 2017

unrestricted union member and exceptions during object construction

Normally you are responsible for lifetime of your unrestricted union members -- and you do it via in-place ctor/dtor calls. But, apparently, there is at least one case when compiler helps you -- in the code below, if object construction fails it's union gets correctly destroyed (at least in MSVC 2015), i.e. we never leak.

struct CanThrow
{
    CanThrow() {  if (rand() == 0) throw 0;  }
};

struct A
{
    A() : str{} {}
    ~A() { str.~basic_string(); }

    union { std::string str; };
    CanThrow ct;
};

Question -- is this guaranteed by standard and where it stipulates that?

Aucun commentaire:

Enregistrer un commentaire