这是正常的 c++ 行为吗?编译器零初始化我的类,尽管有一个用户定义的构造函数

Is this normal c++ behavior? compiler zero initialize my class despite having a user defined constructor

本文关键字:我的 有一个 构造函数 定义 用户 初始化 编译器 c++      更新时间:2023-10-16

让我描述一下我的问题。我已经分析了使用 OllyDbg 使用 Visual Studio 2015 [发布] 生成的以下代码,并且调用了两次 memset(一次为 408 字节,后者为 400 字节)。显然,408字节是编译器对我的类进行零初始化。

为什么会这样?

我的主类已经有一个构造函数,它应该摆脱编译器生成的构造函数。

有趣的是:如果我从主类中删除成员"someotherclas sb",m_buffer只会设置一次(由我设置,有 400 个字节)。

// ConsoleApplication.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
class someotherclas
{
public:
    int * ptr;
};
class mainclass
{
public:
    char m_buffer[400];
    someotherclas sb; //If I remove this, buffer will be memset once only (by me, in the constructor)
    int a;
    mainclass()
    {
        memset(m_buffer, 0x00, sizeof(m_buffer));
        a = 6;
    }
};
int main(int argc, char * arr[])
{
    mainclass * buffer2 = new mainclass;
    return 0;
}

我想发生这种情况是因为为您的项目启用了安全开发生命周期检查。你能检查编译器选项吗?如果是这样,则适用以下规定:

启用/sdl 后,编译器...执行类成员 初始化。自动将所有类成员初始化为零 对象实例化(在构造函数运行之前)。这有助于防止 使用与类成员关联的未初始化数据 构造函数不显式初始化。

相关文章: