1

I have a question about const std::function& as a member variable.
In the below code, I was expecting to see "2" printed out. But on my compiler (gcc c++17), I saw "1", Why?

using Fn = std::function<bool()>; 
class Foo
{
public:
  Foo () {}
  void bar(){
    if(fn_) 
      std::cout<<"1"<<std::endl; 
    else
      std::cout<<"2"<<std::endl; 
  }
private:
  const Fn& fn_ = nullptr; 
};

int main()
{
  Foo f; 
  f.bar();
 }
Ruotong Jia
  • 31
  • 1
  • 3
  • You're storing a reference to a temporary. See this [question](https://stackoverflow.com/questions/10387751/giving-default-values-to-reference-member-variables) or this [other one](https://stackoverflow.com/questions/50823424/initialize-member-reference-with-default-value) for ways to work around this. – 1201ProgramAlarm Nov 28 '21 at 01:12

1 Answers1

1

I think what's happening here is that your line

const Fn& fn_ = nullptr;

is essentially doing

const Fn& fn_ = Fn(nullptr);

So that reference is dangling and you're invoking undefined behaviour by accessing it.

If you do it by value instead of by reference, or if you pass in a valid empty Fn object (with sufficient lifetime) to the constructor to bind the ref member to, the output is what you expect.

John Ilacqua
  • 906
  • 5
  • 19