[英]What does passing curly braces as a function argument mean?
在 C++17 代码中,我有时会看到类似这样的内容:
void myfunction(const std::string& arg1, int arg2) {
//...
}
void otherfunction() {
myfunction("a",1);
myfunction({},2);
myfunction("b",{});
myfunction({},{});
}
空花括号 arguments 是什么意思?
我发现我得到一个空字符串和 0 integer,所以我想这是某种默认值。
这是在 C++17 中引入的,称为列表初始化。
当大括号为空时,它将执行值初始化:
对于诸如int
之类的标量类型,就像您在全局 scope 中定义它一样,即它将被 零初始化(对于具有非用户提供且未删除的默认构造函数的 class 实例也是如此,除非它具有非- 普通的默认构造函数,在这种情况下它将被默认初始化)。
如果 class 类型没有默认构造函数或者默认构造函数已被标记为已删除,它将执行默认初始化(例如T t;
),如果有用户定义的构造函数,也是如此。
例子:
struct A {
A() : x{1}, y{2} {}
int x,y;
};
/* A has a default user-provided constructor,
* calls default constructor */
A a{};
//////////////////////////
struct B {
B() {}
int x, y;
string z;
};
/* B has a user defined default constructor,
* since x and y are not mentioned in the initializer list,
* B::x and B::y contain intermediate values,
* while, B::z will be default initialized to "" */
B b{};
//////////////////////////
struct C {
int x, y;
};
/* C has an implicit default constructor,
* C::x and C::y will be zero-initialized */
C c{};
//////////////////////////
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.