使用花括号初始值设定项的默认参数

Default argument using curly braces initializer

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

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

我曾经使用 void do_somthing(foo x=foo()){} 来默认 x 参数,但我在某些书籍或在线示例中看到这种方式 ={}(不记得了)。使用它完全没问题吗?这两种方法有什么区别吗?

foo x=foo()copy initialization

Initializes an object from another object

foo()value initialization

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

foo x={}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.

所以在这种情况下结果是一样的(都是值初始化的)。

而本例中值初始化的效果是:

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

最终零初始化在这种情况下的效果是:

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.