samedi 22 avril 2017

unrestricted union members lifetime during parent object construction

Normally you are responsible for lifetime of your unrestricted union members -- and typically 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 (previously constructed) union member gets automatically destroyed (at least in MSVC 2015), i.e. we never leak.

#include <string>

struct CanThrow
{
    CanThrow() {  throw 0;  }
};

struct A
{
    A() : str{} {}    // note that we don't explicitly call str dtor here
    ~A() { str.~basic_string(); }

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

int main() { A a; }

Disclaimer: this code compiles on my MSVC 2015

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

Aucun commentaire:

Enregistrer un commentaire