gpt4 book ai didi

c++ - 使用大括号初始值设定项的默认参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:29 31 4
gpt4 key购买 nike

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

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.

关于c++ - 使用大括号初始值设定项的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35910619/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com