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?