Search code examples
c++c++11visual-studio-2012internal-compiler-error

Struct can be declared within method body, but only if it doesn't contain member field initializers. Compiler bug or not?


It took me a good hour to locate this issue. The following code

class Test {
public:
    void method();

    int _member;
};

void Test::method()
{
    struct S {
        int s = 0; // same with int s {0};
    };

    _member;
}

int main(int argc, const char* argv [])
{
    return 0;
}

Produces a compilation error:

1>error C2327: 'Test::_member' : is not a type name, static, or enumerator
1>error C2065: '_member' : undeclared identifier

And the error goes away as soon as I replace int s = 0; with int s;.

This only occurs in MSVC 2013, not 2015. I'm pretty sure it's a compiler bug but I want to make sure it's not some C++ peculiarity that I'm not familiar with (something that changed between C++11 and C++14).


Solution

  • [C++11: 12.6.2] defines NSDMIs in C++11, and neither this section nor any other section in the document defines such a constraint on the syntax. Therefore, it must be an implementation bug.

    And, since GCC, Clang and Visual Studio 2015 all accept the code, I don't think any more detailed investigation is worthwhile.