且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++对象创建和构造函数

更新时间:2023-02-09 15:29:18

我会评论一下第三个第一个:

  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.