1

So I wonder whether the following is allowed:

#include <iostream>

class Foo {
public:
    Foo(const bool& ref) : ref(ref) {}

    const bool& ref;
};

int main()
{
    Foo foo(true);
    std::cout << foo.ref << "\n";

    return 0;
}

So basically I want to store an rvalue as a const lvalue reference member in a class. The question Why is it allowed to pass R-Values by const reference but not by normal reference? says this is allowed when passing the rvalue reference. But I wonder if it's okay to keep that const reference around.

  • @FrançoisAndrieux That is the question. Why or why not is this undefined/defined behaviour. Saying it's a dangling reference is not enough since they are allowed in some cases. Is this one of those cases? If not why. –  Jun 10 '20 at 21:03
  • Can you be specific as to which part of the linked question's accepted answer is unclear to you or seems like it shouldn't apply here? – François Andrieux Jun 10 '20 at 21:04
  • The linked question is a related but a different scenario. I can't blindly apply it to this situation. –  Jun 10 '20 at 21:05
  • The accepted answer is very short, and says "The C++ language says that a local const reference prolongs the lifetime of temporary values until the end of the containing scope". The const reference here is the constructor's argument. It's containing scope is the constructor. The materialized temporary of `true`'s lifetime extends until the end of that scope, the constructor. – François Andrieux Jun 10 '20 at 21:08
  • @FrançoisAndrieux By that logic the rule should extend to class scope. No where does it say this rule only goes one level deep. –  Jun 10 '20 at 21:08
  • http://eel.is/c++draft/class.temporary#6 – Asteroids With Wings Jun 10 '20 at 21:09
  • You are assuming it's transitive. And you are ignoring the "local" part of "local const reference". Maybe that answer needs more details. Consider posting a comment to it. – François Andrieux Jun 10 '20 at 21:09
  • Also https://stackoverflow.com/q/14735630/4386278 ish – Asteroids With Wings Jun 10 '20 at 21:13

0 Answers0