gpt4 book ai didi

C++ 零初始化

转载 作者:IT老高 更新时间:2023-10-28 21:46:33 24 4
gpt4 key购买 nike

根据 http://en.cppreference.com/w/cpp/language/zero_initialization,我无法理解我类(class)中的某个成员何时以及为何被零初始化.

考虑以下测试程序:

#include <iostream>
#include <stdio.h>

class MyTest {
private:
const static unsigned int dimension = 8;
void (* myFunctions [dimension])();

public:
MyTest() {}

void print() {
for(unsigned int i=0; i < MyTest::dimension; i++) {
printf("myFunctions[%d] = %p\n", i, this->myFunctions[i]);
}
}
};


int main() {
//We declare and initialize an object on the stack
MyTest testObj = {};
testObj.print();

return 0;
}

我声明一个类有一个由签名“void functionname()”的 8 个函数指针组成的数组。当我在 main 中将类的对象声明并初始化为 MyTest testObj = {};MyTest testObj; 时,我希望它是零初始化,即所有指针都是空指针。

但是,在我的带有 g++ -m32 -o test -std=c++14 test.cpp && test 机器的 Windows 10 机器上使用 g++ 5.3.0 编译会得到输出:

myFunctions[0] = 76dd6b7d
myFunctions[1] = 00401950
myFunctions[2] = 0061ff94
myFunctions[3] = 004019ab
myFunctions[4] = 00401950
myFunctions[5] = 00000000
myFunctions[6] = 003cf000
myFunctions[7] = 00400080

看起来像堆栈中未初始化的值..

如果我将对象的声明移到 main 之外(作为全局变量),它会再次打印全零。

如果我正确理解了 cppreference,这是因为我有一个具有静态存储持续时间的变量,因此是零初始化的。它通过对我的类的所有非静态数据成员(即 myFunctions)数组进行零初始化来初始化我的类类型。数组是通过对它的每个元素进行零初始化来初始化的,在我的函数指针的情况下,它是一个空指针。

为什么当我使用 MyTest testObj = {}; 声明我的对象堆栈时,它没有对堆栈进行零初始化?

最佳答案

以下

MyTest testObj = {};

MyTest不是零初始化,只是简单地调用其默认构造函数。 cppreference 页面解释了原因(强调我的):

As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided.

MyTest 是一个类类型,a 有一个构造函数。


定义构造函数

MyTest() = default;

将改为零初始化对象。

下面的相关标准引用(强调我的)。

来自 [dcl.init#8] :

To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type with either no default constructor ([class.ctor]) or a default constructor that is user-provided or deleted, then the object is default-initialized;

  • if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;

  • ...

来自 [dcl.init.list] :

List-initialization of an object or reference of type T is defined as follows:

  • ...

  • Otherwise, if the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.

关于C++ 零初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48809894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com