问题描述
原始类型没有构造函数已经被反复强调了.例如,当我调用 Foo()
时,此 _bar
未初始化为 0:
It's been rehashed over and over that primitive types don't have constructors. For example this _bar
is not initialized to 0 when I call Foo()
:
class Foo{
int _bar;
};
显然 int()
不是构造函数.但是是它的名字是什么?
So obviously int()
is not a constructor. But what is it's name?
在这个例子中,我会说 i
是:(构造的?初始化的?吃错的?)
In this example I would say i
is: (constructed? initialized? fooed?)
for(int i{}; i < 13; ++i)
Loki Astari 提到 这里该技术有某种名称.
Loki Astari mentions here that the technique has some sort of name.
编辑以回应 Mike Seymour:
#include <iostream>
using namespace std;
class Foo{
int _bar;
public:
void printBar(){ cout << _bar << endl; }
};
int main()
{
Foo foo;
foo.printBar();
Foo().printBar();
return 0;
}
在 Visual Studio 2013 上运行此代码会产生:
Running this code on Visual Studio 2013 yields:
3382592
3382592
有趣的是 gcc 4.8.1 产量:
Interestingly on gcc 4.8.1 yields:
134514651
0
推荐答案
没错.
例如,当我调用 Foo()
是的.Foo()
指定值初始化,对于像这样没有用户提供构造函数的类,这意味着它在初始化其成员之前是零初始化的.所以 _bar
以零值结束.(尽管如评论中所述,一种流行的编译器没有正确地对此类类进行值初始化.)
Yes it is. Foo()
specifies value-initialisation which, for class like this with no user-provided constructor, means it's zero-initialised before initialising its members. So _bar
ends up with the value zero. (Although, as noted in the comments, one popular compiler doesn't correctly value-initialise such classes.)
如果你改用默认初始化,它不会被初始化.你不能用临时的来做到这一点;但是声明的变量 Foo f;
或 new F
的对象将被默认初始化.原始类型的默认初始化什么都不做,给它们留下一个不确定的值.
It would not be initialised if you were to use default-initialisation instead. You can't do that with a temporary; but a declared variable Foo f;
or an object by new F
will be default-initialised. Default-initialisation of primitive types does nothing, leaving them with an indeterminate value.
如果该类有一个用户提供的默认构造函数,并且该构造函数没有专门初始化 _bar
,它也不会被初始化.同样,它将被默认初始化,没有任何效果.
It would also not be initialised if the class had a user-provided default constructor, and that constructor didn't specifically initialise _bar
. Again, it would be default-initialised, with no effect.
显然 int() 不是构造函数.但它叫什么名字?
作为表达式,它是 int
类型的值初始化临时值.
As an expression, it's a value-initialised temporary of type int
.
从句法上讲,它是显式类型转换(函数式)"的特例;但是将该术语用于除类型转换之外的任何内容都会相当混乱.
Syntactically, it's a special case of an "explicit type conversion (functional notation)"; but it would be rather confusing to use that term for anything other than a type conversion.
在这个例子中,我会说 i
是:(构造的?初始化的?吃错的?)
已初始化.如果您想更具体,列表初始化(带有空列表)、值初始化或零初始化.
Initialised. List-initialised (with an empty list), value-initialised, or zero-initialised, if you want to be more specific.
这篇关于什么是 int() 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!