Search code examples
c++constructordefault-constructor

MSVC2015 initializes class member that should be left uninitialized


I noticed that MSVC2015 initializes data member that should be left to be indeterminate. Code sample and results:

class A
{
public:
    int i;
};

class B
{
public:
    B(){}
    int i;
};

class C
{
public:
    int i;
    virtual void vf(){}
};

int main()
{
    A a;    
    B b;    
    C c;   

    a.i;     //error C4700 uninitialized local variable used
    b.i;     //ok
    c.i;     //ok
}

if I understand it correctly, in both 1, 2, 3 cases, member i should be default initialized, which is doing nothing for non-class type, the error should be issued for all three cases. Is my understanding correct here?

By checking the assembly, a memset is generated in constructor to zero class members, why VS does this? In my understanding, class X's implicit default constructor's semantic should be the same as X(){}, is it right?

And by adding virtual functions, implicit constructor is no longer trivial, but I don't know what difference is if a ctor is trivial or not.


Solution

  • The compiler switch /sdl could be the cause. This is a security feature that zeros memory.

    Look in projection properties -> C++ -> General -> SDL checks

    Also see Security Check (/GS) in projection properties -> C++ -> Code Generation.

    Disable them both and see what happens.