本文介绍了通过默认构造函数语义进行初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对另一个关于此问题的帖子感到困惑:


这种初始化是这样的吗?
int x = int();


初始化为0的类型仅适用于内置类型或*所有* POD类型?


即:


struct any

{

int x,y;

} a = whatever();

是保证ax和ay初始化为0?


-

Ioannis Vranos


I was confused from another thread about this:

Does this kind of initialisation
int x= int();

initialise to 0 of the type only for built in types or for *all* POD types?

That is:

struct whatever
{
int x,y;
}a=whatever();
is guaranteed a.x and a.y to be initialised to 0?

--
Ioannis Vranos

http://www23.brinkster.com/noicys

推荐答案



T x = T();


复制使用默认初始化对象初始化x,无论类型T是什么,

内置,POD或其他。


T x = T();

copy initializes x with a Default-Initialized object regardless of what the type T is,
builtin, POD, or otherwise.




T x = T();

复制使用默认初始化对象初始化x,无论什么是T类型,内置,POD或其他。



T x = T();

copy initializes x with a Default-Initialized object regardless of what the type T is,
builtin, POD, or otherwise.




对于内置类型,这相当于0对应的类型。 />
对于非POD类型,结果与T x(T())相同;

对于除内置类型之外的POD类型,是否与内置?

TC ++ PL仅提供内置类型,用于第一种初始化。


-

Ioannis Vranos






所有POD类型。


此外,在C ++ 2003(但不是C ++ 1998)中,它适用于非POD

结构的POD成员,前提是它们没有明确说明定义的构造函数。


示例:


struct Foo {

int x;

std :: string s;

};


struct Bar {

int x;

std :: string s;

Bar(){}

};


在C ++ 1998中,Foo( ).x未定义;在C ++ 2003中,它是0.


在C ++ 1998和C ++ 2003中,Bar()。x都是未定义的。原因是Bar的

作者有机会初始化x并选择不这样做,

而Foo的作者没有机会初始化x ,

定义了没有提供此类机会的构造函数。



All POD types.

Moreover, in C++2003 (but not C++1998), it works for POD members of non-POD
structures, provided that they have no explicitly defined constructors.

Example:

struct Foo {
int x;
std::string s;
};

struct Bar {
int x;
std::string s;
Bar() { }
};

In C++1998, Foo().x is undefined; in C++ 2003, it''s 0.

In both C++1998 and C++2003, Bar().x is undefined. The reason is that the
author of Bar had the opportunity to initialize x and chose not to do so,
whereas the author of Foo did not have the opportunity to initialize x,
having defined no constructor that would have provided such an opportunity.


这篇关于通过默认构造函数语义进行初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:02