Visual C++ 似乎是零初始化类的 POD 成员,它不应该 [英] Visual C++ seems to be zero-initializing POD members of a class which it shouldn't

查看:19
本文介绍了Visual C++ 似乎是零初始化类的 POD 成员,它不应该的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂这样的课:

class TestClass
{
public:
    TestClass() {};
    //Note: I wish not to initialize rawMemory (for whatever reason)
    int rawMemory[32];
};

int main()
{
    TestClass obj;
    return 0;
}

在我使用 TestClass obj; 创建了一个 TestClass 对象后,我得到了我想要的行为:rawMemory 没有被初始化(在调试模式下用 0xcc 填充,随机释放模式下的不确定值).
当我向类添加指针成员时:

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;
};

rawMemory 被初始化为零!我认为根据标准,这不应该发生.我什至尝试过 std::aligned_storage 专用于保留未初始化的自动内存,但 rawMemory 仍然初始化为零!

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;
};

注意:我试过 g++,它按我的预期工作.
更新:如果我把 TestClass 改成结构体,问题就没有了;如果我给 TestClass 一个默认的隐式构造函数,问题就消失了.

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.

推荐答案

我终于找到了这个问题的根源.
当类中存在指针成员时,Visual C++ 会在调用我定义的构造函数之前插入一个 autoclassinit 方法调用.此方法调用与成员初始化有些混乱,并且它对我的 rawMemory 成员进行了零初始化.
可以通过在 Visual C++ 编译器选项中禁用 /sdl 来消除此行为.但是,如果它不是非常关键的性能(或瓶颈),我的建议是保持原样.
感谢所有试图提供帮助的人!

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!

这篇关于Visual C++ 似乎是零初始化类的 POD 成员,它不应该的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆