奇怪的c ++代码片段 [英] Weird c++ code snippet
问题描述
我有这个片段:
模板< class T&
类VECTOR_2D
{
public:
T x,y;
VECTOR_2D()
:x(T()),y(T())
{}
}
解决方案在构造函数中初始化x和y是什么? div>
x
和y
已复制初始化
从C ++ 03标准,§8.5/ c> T 7:
一个对象的初始值是一个空的圆括号,即()
并从§8.5/ 5开始:
em> value-initialize 类型
T
的对象表示:
- 如果
T
是一个具有用户声明的构造函数的类类型,则调用T
的默认构造函数如果T
没有可访问的默认构造函数,则初始化是错误的);
- 如果
T
是没有用户声明的构造函数的非联合类类型,则T
的每个非静态数据成员和基类组件都是值初始化的;
- 如果
T
是数组类型,则每个元素都被初始化;
- 否则,对象是零初始化
要初始化<$ c $ < c> T 表示:
- 如果
T
一个标量类型,对象设置为0
(零)转换为T
;
- 如果
T
是非联合类类型,每个非静态数据成员和每个基类子对象都是零初始化的;
- 如果
T
是联合类型,对象的第一个命名数据成员)是零初始化的;
- if
T
是一个数组类型,每个元素都是零初始化的;
- 如果
T
是引用类型,不执行初始化。
$ b b
x(T()),y(T())
可以替换为x c $ c>直接替换为value-initialize
x
和y
。在大多数情况下,这将实现相同的净效果(假设T
是可复制构造的),但在某些情况下,这将更有效,因此作为一般规则,I have this snippet:
template<class T> class VECTOR_2D { public: T x,y; VECTOR_2D() :x(T()),y(T()) {} }
What are x and y initialized to in the constructor?
解决方案
x
andy
are copy-initialized toT
's value-initialized value.From the C++03 standard, §8.5/7:
An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.
And from §8.5/5:
To value-initialize an object of type
T
means:
- if
T
is a class type with a user-declared constructor, then the default constructor forT
is called (and the initialization is ill-formed ifT
has no accessible default constructor);- if
T
is a non-union class type without a user-declared constructor, then every non-static data member and base-class component ofT
is value-initialized;- if
T
is an array type, then each element is value-initialized;- otherwise, the object is zero-initialized
To zero-initialize an object of type
T
means:
- if
T
is a scalar type, the object is set to the value of0
(zero) converted toT
;- if
T
is a non-union class type, each nonstatic data member and each base-class subobject is zero-initialized;- if
T
is a union type, the object’s first named data member) is zero-initialized;- if
T
is an array type, each element is zero-initialized;- if
T
is a reference type, no initialization is performed.
x(T()),y(T())
could be replaced withx(),y()
to instead value-initializex
andy
directly. In most circumstances this will achieve the same net effect (assumingT
is copy constructable), but in some cases this will be more efficient, so as a general rule this approach should always be preferred.这篇关于奇怪的c ++代码片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文