0

I understand the risk of a temporary being bound to a member reference: any use of the member after the constructor will be a use after free.

However, in the following code I'm not binding a temporary to a member reference:

#include <iostream>
#include <string>

using namespace std;

class Test
{
public:
    Test(const string& a)
      : a_{a}
    { }

    void printA() { cout << a_ << endl; }

private:
    const string& a_;
};

int main()
{
    string s = "ada";
    Test t(s);
    t.printA();
}

Compiled with -Werror=extra in gcc 4.8, I get the following:

$ g++ -std=c++11 -Werror=extra -Wall test.cc -o test && ./test
test.cc: In constructor ‘Test::Test(const string&)’:
test.cc:10:13: error: a temporary bound to ‘Test::a_’ only persists until the constructor exits [-Werror=extra]
       : a_{a}
             ^
cc1plus: some warnings being treated as errors

This seems like a compiler warning bug to me since "ada" is a string stored in the named variable s and is therefore not a temporary. In fact I notice that if I change the type of a_ to an int instead of a std::string I no longer get the warning.

Of course it could be that I'm missing something and I am doing something wrong. Am I misunderstanding something?

firebush
  • 5,180
  • 4
  • 34
  • 45
  • The compiler only looks at the constructor itself. There's a potential for passing a temporary to it, which would then be bound to a reference. The compiler issues a warning to this effect, which you choose to treat as an error. The compiler cannot be expected to analyze the whole program to prove that a temporary is never passed to this constructor (it cannot even if it wanted to - the offending call may be in a different translation unit). – Igor Tandetnik Jun 06 '19 at 14:57
  • 2
    Looks like a bug. Newer versions don't trigger: https://godbolt.org/z/jkrd6I – NathanOliver Jun 06 '19 at 14:59
  • 1
    No error starting with gcc 4.9. Clear bug. On a side note, may be it's a high time to upgrade to something more modern? – SergeyA Jun 06 '19 at 15:00

0 Answers0