gpt4 book ai didi

c++ - C++中函数指针的默认值

转载 作者:可可西里 更新时间:2023-11-01 18:41:43 24 4
gpt4 key购买 nike

C++ 中函数指针的默认值是多少? (显然它不能是NULL,那它是什么?)

这个程序应该如何运行,为什么?

struct S { void (*f)(); };

int main()
{
S s = S();
s.f(); // What is the value of s.f?
}

最佳答案

第一个任何指针可以为空。这是关于指针的一个普遍真理。也就是说,您的为空,但不一定是出于您可能认为的原因;

C++11 § 8.5,p10

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

这很重要,因为您的声明包括:

S s = S();

根据值初始化的定义:

C++11 § 8.5,p7

To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

  • if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.

  • if T is an array type, then each element is value-initialized;

  • otherwise, the object is zero-initialized.

这让我们了解了将您的对象类型零初始化意味着什么:

C++11 § 8.5,p5

To zero-initialize an object or reference of type T means:

  • if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T (103)

  • if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;

  • if T is a (possibly cv-qualified) union type, the object’s first non-static named data member is zero- initialized and padding is initialized to zero bits;

  • if T is an array type, each element is zero-initialized;

  • if T is a reference type, no initialization is performed.

103) As specified in 4.10, converting an integral constant expression whose value is 0 to a pointer type results in a null pointer value.

后者是您指针为空的原因。给定相同的代码,但将 s 的声明更改为:

S s;

给定像上面这样的声明,通过标准采取不同的路径:

C++11 § 8.5,p11

If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value. [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2.

然后引出了最后一个问题,什么是默认初始化:

C++11 § 8.5,p6

To default-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

  • if T is an array type, each element is default-initialized;

  • otherwise, no initialization is performed.

关于c++ - C++中函数指针的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14829158/

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