c++ - How to control the copy of return object into a new object? -


This code is overloaded in order to control operator behavior for the operator = class A objects, and the copy constructor was also declared to see that it was used for the copy process.

My question is, the compiler, a_object + b_object in c_object if the copy constructor and assignment operator was not used as shown in the output ? And in this case how to control the copy behavior?

  #include & lt; Iostream & gt; #deleted panellines (x) std :: cout & lt; & Lt; X & lt; & Lt; "---------------------------- \ n"; Class A {IIT value; Public: A (Int V = 0): Value (v) {} A (Constant A and A) {std :: cout & lt; & Lt; "CUSTOM CREATOR ... \ n"; Value = a.value; } Consta and A. Operator = (Constant A & A) {std :: cout & lt; & Lt; "= Operator ... \ n"; This- & gt; Value = a.value; Return * This; } Const. One operator + (Constant A & A) {Return A (Value + A. Value); } Zero print (std :: ostream & os) {OS & lt; & Lt; Price & lt; & Lt; Std :: endl; }}; Int main () {one a_object (10); A b_object (20); PUTLINE (1); One c_object = a_object + b_object; // What does the compiler do to make this copy? PUTLINE (2); A d_object = c_object; PUTLINE (3); C_object.print (std :: court); PUTLINE (4); D_object.print (std :: court); PUTLINE (5); A_object = c_object; PUTLINE (6); A_object.print (std :: court); }  

Outputs look like this:

  1 --------------------- - ------ 2 ---------------------------- Copy creator ... 3 -------- - ------------------- 30 4 ---------------------------- 30 5 ---------------------------- = Operator ... 6 --------------  
Experience and in some situations, the compiler is allowed to create a blank object directly in the destination, copy it by making it temporary.

It's okay what's going on in your case: return value operator + to c_object in the space (int) Constructor is created, so you will not see the call to the copy constructor.

With GCC, you can pass the command-line flag -fno-elide-constructors , which prevents the copy elision. You will then see all the copy creator calls. .


Comments

Popular posts from this blog

c# - SignalR: "Protocol error: Unknown transport." when navigating to hub -

c# - WPF Expander overlay used in ItemsControl -

class - Kivy: how to instantiate a dynamic classes in python -