使用花括号初始化程序的默认参数 [英] Default argument using curly braces initializer

查看:112
本文介绍了使用花括号初始化程序的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的这段代码似乎运行良好:

  class foo {/ *一些成员变量和函数* /}; 
void do_somthing(foo x = {}){}
int main(){
do_somthing();
}

我以前使用 void do_somthing(foo x = foo()){} 默认为 x 自变量,但我以这种方式看到 = {} 在某些书或在线示例中(不记得了)。使用它完全可以吗?两种方法之间有什么区别?

解决方案

foo x = foo()复制初始化


从另一个对象初始化一个对象


foo( )值初始化


这是使用空的初始化程序构造变量时执行的初始化。


foo x = {} 汇总初始化


如果初始化子句的数量少于
成员和基数的数量(自C ++ 17起),则从braced-init-list



初始化聚合。或初始值设定项列表完全为
为空,其余成员和基数(自C ++ 17起)由其缺省初始值设定项(如果在类定义中提供,则
初始化,否则由
初始化) ++ 14)通过空列表执行
值初始化


在这种情况下(两个值都已初始化)结果是相同的。



在这种情况下,值初始化的效果是:


如果T是具有默认构造函数的类类型,该构造函数既不是用户提供的,也不是删除的d(也就是说,它可能是具有隐式定义或默认默认构造函数的类),该对象被零初始化


最后,在这种情况下,零初始化的影响是:


如果T是标量类型,则对象的初始值为整数$ b $

如果T是非联合类类型,则所有基类和非静态数据
成员都将初始化为零。 ,并且所有填充都初始化为零
位。



I have this snippet of code which seems to work well:

class foo{/* some member variables and functions*/};
void do_somthing(foo x={}){}
int main(){
  do_somthing();
}

I used to use void do_somthing(foo x=foo()){} to default the x argument but I see this way ={} in some book or online example(can not remember). Is it totally ok to use it? Is there any difference between the two methods?

解决方案

foo x=foo() is copy initialization,

Initializes an object from another object

and foo() is value initialization.

This is the initialization performed when a variable is constructed with an empty initializer.

foo x={} is aggregate initialization.

Initializes an aggregate from braced-init-list

If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, which performs value-initialization.

So the result is the same in this case (both value-initialized).

And the effects of value initialization in this case are:

if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized

Finally the effects of zero initialization in this case are:

If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T.

If T is an non-union class type, all base classes and non-static data members are zero-initialized, and all padding is initialized to zero bits. The constructors, if any, are ignored.

这篇关于使用花括号初始化程序的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆