C ++构造函数语法 [英] C++ constructor syntax

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

问题描述

简单的问题:以下语句是否等同?或者是第二个在幕后做更隐含的事情(如果是,什么?)

Simple question: are the following statements equivalent? or is the second one doing more implicit things behind the scenes (if so, what?)

myClass x(3);
myClass x = myClass(3);


$ b

谢谢!

Thanks!

推荐答案

它们不完全相同。第一个称为直接初始化,第二个称为复制初始化。

They are not completely identical. The first is called "direct initialization" while the second is called "copy initialization".

现在,标准组成了两条规则。第一种是用于直接初始化和用于复制初始化,其中初始化器是初始化对象的类型。第二个规则是在其他情况下进行副本初始化。

Now, the Standard makes up two rules. The first is for direct initialization and for copy initialization where the initializer is of the type of the initialized object. The second rule is for copy initialization in other cases.

因此,从这个角度来看,两者都被称为第一个规则。在您具有相同类型的副本初始化的情况下,编译器允许删除副本,因此它可以构建您直接创建到初始化对象中的临时。所以你可以很好地用相同的代码生成。但是拷贝构造函数,即使拷贝被省略(优化出来),仍必须可用。也就是说,如果你有一个私有拷贝构造函数,如果代码出现的代码无法访问它,那么该代码是无效的。

So, from that point of view both are termed in one - the first - rule. In the case where you have copy initialization with the same type, the compiler is allowed to elide a copy, so it can construct the temporary you create directly into the initialized object. So you can end up very well with the same code generated. But the copy constructor, even if the copy is elided (optimized out), must still be available. I.e if you have a private copy constructor, that code is invalid if the code in which it appears has no access to it.

第二种方法称为复制初始化,因为如果初始化程序的类型是不同类型,则会创建一个临时对象,试图将右侧隐式转换为左侧:

The second is called copy-initialization, because if the type of the initializer is of a different type, a temporary object is created in trying to implicitly convert the right side to the left side:

myclass c = 3;

编译器创建一个类型为myclass的临时对象,然后当有一个构造函数。然后它用该临时对象初始化对象。同样在这种情况下,临时创建的可以直接在已初始化的对象中创建。您可以通过在类的构造函数/析构函数中打印消息并使用GCC的选项 -fno-elide-constructors 来执行以下步骤。它不试图去复制当时。

The compiler creates a temporary object of the type of myclass then when there is a constructor that takes an int. Then it initializes the object with that temporary. Also in this case, the temporary created can be created directly in the initialized object. You can follow these steps by printing messages in constructors / destructors of your class and using the option -fno-elide-constructors for GCC. It does not try to elide copies then.

在旁注中,上面的代码与赋值运算符无关。在这两种情况下,发生的是初始化。

On a side-note, that code above has nothing to do with an assignment operator. In both cases, what happens is an initialization.

这篇关于C ++构造函数语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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