Search code examples
c++visual-studiovisual-c++initializationmember-initialization

Missing MSVC initializer list use before initialization error


How can I make MSVC/visual studio give an error about the member m_second being used before being initialized below?

This is similar but different to C5038 an error about the initialization order (commented line).

https://godbolt.org/z/P6TPG5W7E

class MyClass {
public:
    MyClass() : m_first(m_second) {}
    //MyClass() : m_second(123), m_first(m_second) {}
    int m_first;
    int m_second = 42;
};

int test() {
    MyClass obj;
    return obj.m_first;
}

Solution

  • In Visual Studio, run Code Analysis -> get warning C26495.

    Project properties -> Code Analysis -> Enable Code analysis on build.

    Warnings can be treated as errors by configuring a ruleset.

    For Godbolt, there is Add tool:

    enter image description here

    I haven't found any parameters suitable for static analysis yet.