PlinyTheElder
PlinyTheElder

Reputation: 1494

Visual Studio 2017 allows a reference member to be initialized with itself in the constructor. Is it really legal C++?

I've just found a pretty dangerous bug in my code, and I feel like it should have been caught by the compiler. Am I wrong? In essence, a reference member of a class is allowed to be initialized by itself in the constructor. Here's the test code that compiles in Visual Studio 2017 without errors or warnings:

struct foo
{
    foo() : reference(reference) {}

    int& reference;
};

int main()
{
    foo fooOb;
}

UPDATE: I see that there is a similar question from 2009 here. Do other compilers behave the same in 2017, or is it a VS 2017 issue? If they do, it kinda suggests to me that this is legal C++, but I don't see how it could be.

Upvotes: 4

Views: 241

Answers (2)

user7860670
user7860670

Reputation: 37587

MSVC 2017 yields:

warning C26495: Variable 'foo::reference' is uninitialized. Always initialize a member variable (type.6)

You may need to enable code analysis by going to Project Properties -> Code analysis (/analyze)

Upvotes: 2

Acorn
Acorn

Reputation: 26076

Do other compilers behave the same in 2017, or is it a VS 2017 issue?

At the time this is written:

  • GCC and Clang both warn, with -Winit-self and -Wuninitialized respectively.

  • Neither MSVC nor ICC warn about it.

If they do, it kinda suggests to me that this is legal C++, but I don't see how it could be.

It is legal in the sense that the compiler is not required to fail compilation, but this is never what you want, since you will trigger UB.

Upvotes: 3

Related Questions