glades
glades

Reputation: 4759

Lifetime extension of default initialized const ref& in an aggregate

I know that binding prvalues to const ref variables will extend the lifetime of the temporary. Now I thought I'd be clever to have a struct options that contains a const ref field B_options (which is used for initializing a subclass in my context). So when I copy this object into the class it will only take space of one reference instead of containing the whole subclass options as well. I compiled this code in gcc and it works perfectly well:

Demo

#include <cstdio>

struct B_options
{
    int a = 10;
};

struct options
{
    const B_options& b_cfg = {};
};

int main()
{
    options cfg = {};

    printf("b_cfg = %d", cfg.b_cfg.a);
}

Then out of curiostiy I tried to compile it with clang trunk and out comes the following error:

<source>:15:20: warning: sorry, lifetime extension of temporary created by aggregate initialization using default member initializer is not supported; lifetime of temporary will end at the end of the full-expression [-Wdangling]
    options cfg = {};
                   ^
<source>:10:22: note: initializing field 'b_cfg' with default member initializer
    const B_options& b_cfg = {};

Now... is this UB or just something that clang can't do right now? I'm on gcc so I could live with clang just not implementing stuff, but I'm not that comfy venturing to UB land.

Upvotes: 2

Views: 33

Answers (0)

Related Questions