问题描述
我现在正在学习转换器,并有几个问题。在这些行:
Foo obj(args);
Foo obj2;
obj = Foo(args);
Foo obj3 = Foo(args);
第一部分:只有一个构造函数称为(Foo) $ c> obj 被初始化。
:创建临时对象 obj2
调用它的默认ctor。接下来,我们创建另一个 Foo
的副本,并将它的副本传递给 operator =()
。是对的吗?因此,3个本地临时对象,2个构造函数调用。 第三部分:create 1 object Foo
并将它的副本传递给 operator =()
。所以,2个临时对象和1个ctor调用。
我理解这个权利吗?
我会评论一下第三个第一个:
Foo obj3 = Foo(args);
不使用 operator =
称为拷贝分配。相反,它调用copy-constructor(理论上)。这里没有分配。所以理论上,有两个对象创建,一个是临时的,另一个是 obj3
。编译器可能优化代码,完全省略临时对象的创建。
现在,第二个:
Foo obj2; //一个对象创建
obj = Foo(args); //在RHS上创建临时对象
这里,第一行创建一个对象,调用默认构造函数。然后它调用 operator =
传递从表达式 Foo(args)
创建的临时对象。因此,有两个对象只有 operator =
接受 const
引用的参数(这是它应该做的)。
关于第一个,你说得对。
I'm learning ctors now and have a few question. At these lines:
Foo obj(args);
Foo obj2;
obj = Foo(args);
Foo obj3 = Foo(args);
First part: only 1 constructor called (Foo) and obj
is initialized. So, 1 object creation.
Second part: creating of temporary object obj2
, calling default ctor for it. Next lines we create another copy of Foo
and pass it's copy into operator=()
. Is that right? So, 3 local temporary objects, 2 constructor callings.
Third part: create 1 object Foo
and pass it's copy into operator=()
. So, 2 temprorary objects and 1 ctor calling.
Do I understand this right? And if it's true, will compiler (last gcc, for example) optimize these in common cases?
I will comment on the third one first:
Foo obj3=Foo(args);
It doesn't use operator=
which is called copy-assignment. Instead it invokes copy-constructor (theoretically). There is no assignment here. So theoretically, there is two objects creation, one is temporary and other is obj3
. The compiler might optimize the code, eliding the temporary object creation completely.
Now, the second one:
Foo obj2; //one object creation
obj = Foo(args); //a temporary object creation on the RHS
Here the first line creates an object, calling the default constructor. Then it calls operator=
passing the temporary object created out of the expression Foo(args)
. So there is two objects only the operator=
takes the argument by const
reference (which is what it should do).
And regarding the first one, you're right.
这篇关于C ++对象创建和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!