构造函数初始化 Vs 赋值 [英] Constructor initialization Vs assignment

查看:29
本文介绍了构造函数初始化 Vs 赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下类

class test1
{
    private:
        int a;
        int b;
    public:
        test1():a(0),b(0){}
};

class test2
{
    private:
        int a;
        int b;
    public:
        test2()
        {
            a=0;
            b=0;
        }
};

现在,我知道 test1() 构造函数是初始化 class 的数据成员的正确方法,因为在 test2() 中> 我们正在执行分配而不是初始化.我的问题是:

Now, I know that test1() constructor is the right way to initialize the data members of a class, because in test2() we are performing assignment and not initialization. My questions are:

  1. 如果我们执行赋值而不是初始化会出现什么问题?
  2. test1() 构造函数的情况下,编译器是否在内部执行赋值?如果没有,那么这些是如何初始化的?
  1. What might go wrong if we perform assignment instead of initialization?
  2. Doesn't the compiler internally perform assignment in case of test1() constructor? If not, then how are these initialized?

推荐答案

如果我们执行赋值而不是初始化会出现什么问题?

What might go wrong if we perform assignment instead of initialization?

某些类类型(以及引用和const 对象)无法赋值;有些不能被默认初始化;有些默认初始化和重新分配可能比直接初始化更昂贵.

Some class types (and also references and const objects) can't be assigned; some can't be default-initialised; some might be more expensive to default-initialise and reassign than to initialise directly.

在 test1() 构造函数的情况下,编译器不是在内部执行赋值吗?如果没有,那么这些是如何初始化的?

Doesn't the compiler internally performs assignment in case of test1() constructor? If no then how are these initialized?

在像 int 这样的原始类型的情况下,两者之间几乎没有或没有实际区别.默认初始化什么都不做,直接初始化和赋值本质上都是一样的.

In the case of primitive types like int, there is little or no practical difference between the two. Default-initialisation does nothing, and direct-initialisation and assignment both do essentially the same thing.

在类类型的情况下,默认初始化、赋值和直接初始化各自调用不同的用户定义函数,有些操作可能根本不存在;所以总的来说,这两个例子可能有非常不同的行为.

In the case of class types, default-initialisation, assignment and direct-initialisation each call different user-defined functions, and some operations may not exist at all; so in general the two examples could have very different behaviour.

这篇关于构造函数初始化 Vs 赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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