Eddy Pronk
Eddy Pronk

Reputation: 6695

Initialising a reference member with itself legal?

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?

Upvotes: 14

Views: 366

Answers (2)

janks
janks

Reputation: 2158

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;
}

Upvotes: 2

BjoernD
BjoernD

Reputation: 4780

Self-assignment is allowed in C / C++ (and I'd consider this a flaw in the language).

From the memory model's point of view, Foo::a_ is simply some memory location and in the initializer list it gets assigned the value of another memory location, which in this special case unfortunately is the same location.

There is a similar flaw in C, where you can do this:

  void foo() 
  {
    int i = i;
  }

Upvotes: -1

Related Questions