没有初始化列表与初始化列表与空对的括号 [英] No initializer list vs. initializer list with empty pairs of parentheses

查看:1040
本文介绍了没有初始化列表与初始化列表与空对的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此主题的复制粘贴在构造函数中初始化字段 - 初始值列表与构造函数体

This is copy paste from this topic Initializing fields in constructor - initializer list vs constructor body

作者解释了以下等价:

    public : Thing(int _foo, int _bar){
        member1 = _foo;
        member2 = _bar;
    }

is equivalent to

    public : Thing(int _foo, int _bar) : member1(), member2(){
        member1 = _foo;
        member2 = _bar;
    }

我的理解是


  • snippet 1是默认初始化的情况(因为没有初始化器列表)

  • snippet 2是值初始化空对括号)。

这两个是等效的吗?

推荐答案

您的理解是正确的(假设 member1 member2
有类型`int)。这两种形式是不是等效的;在
中,成员不会被初始化,并且直到它们被分配之前不能被
使用。在第二种情况下,
成员将被初始化为0.如果成员是具有用户定义的
构造函数的类类型,则两个公式只有
等效。

Your understanding is correct (assuming member1 and member2 have type `int). The two forms are not equivalent; in the first, the members are not initialized at all, and cannot be used until they have been assigned. In the second case, the members will be initialized to 0. The two formulations are only equivalent if the members are class types with user defined constructors.

这篇关于没有初始化列表与初始化列表与空对的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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