[英]Template argument default value for built-in types
Consider this function: 考虑这个功能:
template <typename T>
T foo(const T& var = T()) {
return var;
}
This call is obviously safe: 这个电话显然是安全的:
foo<std::string>()
Are those? 那些是吗?
foo<int>()
foo<bool>()
...
Yes, they are perfectly fine. 是的,他们完全没问题。 An expression of the form
T()
creates an object of type T
and value-initializes it. T()
形式的表达式创建一个T
类型的对象并对其进行初始化。 Value-initializing an int
or bool
is the same as zero-initializing them. 初始化
int
或bool
的值与初始化它们相同。 That is, the parameter var
will have value 0. 也就是说,参数
var
值为0。
The expression
T()
, whereT
is a simple-type-specifier or typename-specifier for a non-array complete object type [...] creates a prvalue of the specified type, whose value is that produced by value-initializing (8.5) an object of typeT
表达式
T()
,其中T
是非数组完整对象类型的简单类型说明符或类型名称说明 符 [...]创建指定类型的prvalue,其值是由值初始化生成的( 8.5)T
类型的对象
Value-initialization is defined as: 值初始化定义为:
To value-initialize an object of type
T
means:对值类型
T
的对象进行值初始化意味着:
if
T
is a (possibly cv-qualified) class type [...]如果
T
是(可能是cv限定的)类类型[...]if
T
is a (possibly cv-qualified) non-union class type [...]如果
T
是(可能是cv合格的)非联盟类类型[...]if
T
is an array type, [...]如果
T
是数组类型,[...]otherwise, the object is zero-initialized.
否则,该对象被零初始化。
Zero-initialization is defined as: 零初始化定义为:
To zero-initialize an object or reference of type
T
means:零初始化
T
类型的对象或引用意味着:
if
T
is a scalar type (3.9), the object is set to the value0
(zero), taken as an integral constant expression, converted toT
;如果
T
是标量类型(3.9),则将对象设置为值0
(零),作为整数常量表达式,转换为T
;[...]
[...]
The temporary object created by T()
is then bound to the const
reference, which extends its lifetime. 然后,由
T()
创建的临时对象绑定到const
引用,从而延长其生命周期。
There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression.
有两种情况,临时表在与完整表达结束时不同的地方被摧毁。 [...] The second context is when a reference is bound to a temporary.
[...]第二个上下文是指引用绑定到临时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.