Reputation: 4850
I have a class like this:
class TestClass
{
public:
TestClass() {};
//Note: I wish not to initialize rawMemory (for whatever reason)
int rawMemory[32];
};
int main()
{
TestClass obj;
return 0;
}
And after I created a TestClass
object using TestClass obj;
I got the behavior I wanted: rawMemory did not get initialized (filled with 0xcc in debug mode and with random undetermined value in release mode).
How ever when I added a pointer member to the class:
class TestClass
{
public:
TestClass() {};
int rawMemory[32];
int* ptr;
};
The rawMemory
got initialized to zero! I think according to the standard this should not happen. I even tried with std::aligned_storage
which is dedicated for reserving uninitialized automatic memory, and rawMemory
still got zero-initialized!
class TestClass
{
public:
TestClass() {};
std::aligned_storage<sizeof(int), alignof(int)>::type rawMemory[32];
int* ptr;
};
Note: I have tried g++, it worked as I expected.
Update: If I change TestClass into a struct, the problem is gone; If I give TestClass
a default implicit constructor the problem is gone.
Upvotes: 2
Views: 221
Reputation: 4850
I have finally found the source of this issue.
When a pointer member is present in the class, Visual C++ inserts a autoclassinit
method call before calling the constructor I defined. This method call somewhat messed up with member initialization, and it did zero-initialized my rawMemory
member.
This behavior can be removed by disabling /sdl
in the Visual C++ compiler options. However, if it is not very performance-critical (or the bottleneck), my suggestion is to leave it as it is.
Thanks to everyone who tried to help!
Upvotes: 4