成员初始化器列表中的初始化 [英] Initialisation in Member Initializer List

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

问题描述

  class A 
{
public:
int a,b;
A():a(1)
{
b = 3;
}
};

如果我们创建此类的对象:

  A obj; 

那么将先初始化, a b



在赋值 b = 3 的过程中,是否会涉及到默认构造函数?我指的是提供的答案:如果使用赋值,那么字段将首先使用默认构造函数初始化,然后重新赋值(通过赋值运算符)与实际值。

mem-initializer 它们在类定义中声明,然后执行构造函数的主体。



对于C ++标准草案的参考说明:






  • 然后,非静态数据成员按它们在类定义中声明的顺序初始化


  • 最后,执行构造函数体的复合语句

    / ul>

    如果您未在构造函数正文中为 b 它会有一个不确定的值。



    要澄清回答你提到的,你似乎指的答案的部分是:


    那么字段将首先用
    默认构造函数初始化,然后通过赋值运算符重新赋值
    和实际值。


    他们的意思是,它将是默认初始化的,在 int 意味着一个不确定的值,从草案C ++标准:


    如果没有为一个对象指定初始化器,则该对象是
    默认初始化的。当获得具有自动或
    动态存储持续时间的对象的存储时,该对象具有不确定的
    值,并且如果不对该对象执行初始化,则该
    对象保持不确定的值,直到该值替换为
    (5.17)。


    注意使用不确定值是未定义的行为


    class A
    {
      public:
        int a ,b;
        A() : a(1)
        {
          b=3;
        }
    };
    

    If we create an object of this class:

    A obj;
    

    then which one will be initialized first, a or b?

    In the process of assigning b = 3 will there be any involvement of default constructor? I'm referring to the answer provided: If you use assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.

    解决方案

    mem-initializer are performed first in the order they were declared in the class definition and then the body of the constructor is executed.

    For reference the draft C++ standard says:

    In a non-delegating constructor, initialization proceeds in the following order:

    [...]

    • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

    • Finally, the compound-statement of the constructor body is executed

    If you did not assign a value to b in the body of the constructor it would have an indeterminate value.

    To clarify from the answer you mentioned, the part of the answer you seem to be referring to is:

    if you use assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.

    what they meant to say was that it would be default initialized which in the case for an int means an indeterminate value, from the draft C++ standard:

    If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17).

    Note that using an indeterminate value is undefined behavior.

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

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