2

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.

glades
  • 3,778
  • 1
  • 12
  • 34
  • Sorry, I've initially pasted the wrong link. I guess this may shed some light on the topic: https://stackoverflow.com/questions/65528744/validity-and-or-lifetime-extension-of-mem-initializer-in-aggregate-initializatio It's about rvalue references, but they behave analogically in terms of lifetime extension. – alagner Mar 14 '23 at 10:57
  • @alagner Interesting, apparently that is an ongoing discussion in [CWG](https://cplusplus.github.io/CWG/issues/2669.html). I would side with gcc and say this is well formed just because it is really handy x) – glades Mar 14 '23 at 11:06
  • @glades, do you have a link to an active discussion on this subject?! – Red.Wave Mar 16 '23 at 12:28
  • @Red.Wave I do not unfortunately. – glades Mar 17 '23 at 06:07

0 Answers0