Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value-initialization of a const member reference

Tags:

c++

reference

I am looking at code of the following form:

class foo
{
  public:
    foo() {}

  //...
};

class bar
{
  public:
    bar() : ref() {}

  private:
    const foo &ref;
};

Is initializing a reference using a temporary in this way correct? I know that it is possible to initialize a const reference that's a local variable with a temporary, and that doing so extends the lifetime of the temporary, e.g.

const foo &tmp = funcThatReturnsByValue(); //OK

However, one of the answers to the related initialize reference in initialization list suggests that there is a difference between "short-lived" and "long-lived" references, and that initializing ref as above is undefined behavior (even though ref is a const reference).

12.2.5 in the standard says, in part, "A temporary bound to a reference member in a constructor's ctor-initializer persists until the constructor exits." Is that describing this situation?

like image 909
user168715 Avatar asked Nov 10 '10 19:11

user168715


3 Answers

This code is ill-formed. You can't default initialize or value initialize a reference.

If you actually had an expression inside of ref(), then yes, 12.2.5 would apply and the temporary would be destroyed when the constructor exits.

like image 54
James McNellis Avatar answered Oct 24 '22 02:10

James McNellis


Your example isn't creating a temporary - to do that you need to change to:

    bar() : ref(foo()) {} 

Now you're binding the reference to a temporary, and that temporary object will be destroyed at the end of the constructor. Your reference will be invalid, and that is Not A Good Thing.

like image 2
Mark Ransom Avatar answered Oct 24 '22 03:10

Mark Ransom


I guess what you want to do is:

bar() : ref(foo()) {}

but don't naively think that the lifetime of a temporary is extended until there's a reference to it. No, it actually is not. So, whether const or not, you sould initialize the reference with a normal object.

like image 1
Armen Tsirunyan Avatar answered Oct 24 '22 03:10

Armen Tsirunyan