Warning for initializing a reference with literal

Hi,

would it be possible to emit a warning for the code below? I could imagine this case could be detected easily in the frontend / middleend.

ASan finds this with detect_stack_use_after_return enabled, but this option is sometimes not feasible due to high memory usage.

struct RefStorer
{
  RefStorer(const bool& ref): m_ref(ref) {}

  const bool& m_ref;
};

RefStorer getRefStorer()
{
  return RefStorer(false); // false passed as reference
}

int main()
{
  RefStorer r = getRefStorer(); // m_ref now dangling
  return 0;
}

Thanks and Best regards,
Martin

Hello!

It's not enough to just warn about passing literal. Imagine the user fixes the warning like this:

RefStorer getRefStorer()
{
  bool b = false;
  return RefStorer(b);
}

If warning goes away with this solution, I guess many users will probably do that.

We need path sensitive analysis.

Writing a warning for this bug sounds very good, if we add a proper path sensitive check.

Best regards,
Daniel Marjamäki

..................................................................................................................
Daniel Marjamäki Senior Engineer
Evidente ES East AB Warfvinges väg 34 SE-112 51 Stockholm Sweden

Mobile: +46 (0)709 12 42 62
E-mail: Daniel.Marjamaki@evidente.se

www.evidente.se

We need path sensitive analysis.

I agree, those more complicated cases should be detected as well (including a helpful warning text that makes it clear why this is bad)

Should I file an (enhancement) bug?

Best regards,
Martin

Should I file an (enhancement) bug?

yes please.

Best regards,
Daniel Marjamäki

..................................................................................................................
Daniel Marjamäki Senior Engineer
Evidente ES East AB Warfvinges väg 34 SE-112 51 Stockholm Sweden

Mobile: +46 (0)709 12 42 62
E-mail: Daniel.Marjamaki@evidente.se

www.evidente.se

Bug 32800 - Emit warning for initializing a reference with literal/temporary
https://bugs.llvm.org//show_bug.cgi?id=32800

Best regards,
Martin