Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising a reference member with itself legal?

Tags:

c++

This was a bug I found in a server application using Valgrind.

struct Foo
{
    Foo(const std::string& a)
        : a_(a_)
    {
    }
    const std::string& a_;
};

with gcc -Wall you don't get a warning. Why is this legal code?

like image 997
Eddy Pronk Avatar asked Apr 08 '10 13:04

Eddy Pronk


1 Answers

What you've got violates 8.3.2/4 A ... reference shall be initialized to refer to a valid object or function. So it is most certainly illegal.

Note that not all erroneous programs are required to be detected by the compiler, although I honestly would have thought this was one of them.

For what it's worth, g++ version 4.4.1 with maximal compiler warnings turned on happily accepts this program without a warning either:

int main(void)
{   
    int *p = 0;
    *p = 5;
}
like image 63
janks Avatar answered Nov 11 '22 11:11

janks