Confused return by value

zhaozj2021-02-11  181

The problem begins here. Class X; Const X Operator (Const X & X1, Const X & X2); X foo () {RETURN X (A B);} and x foo () {x xx (A B); Return XX;} What is the difference? This problem involves the internal processing of C , which is the more common mode. X foo () {x xx; // process ... return;} C how to deal with Return By Value, the traditional method is to modify the prototype. Void foo (x & r) {x xx; xx.x (); // ctor // process ... r.xx (xx) // copy ctor} This will return the value of XX to the return, here there is an XX Temporary objects CTOR and DTOR. Else. X Obj = foo (); transformed into x Obj; foo (obj); however, for programmers, it is possible to optimize, the method is to return, x foo () {return x (.) The compiler has been processed, for this. Void foo (x & r) {return R.X (...);} Did you see it? The CTOR and DTOR of this less object (i.e., the above XX) are naturally improved. Further, if this function is inline, X Obj = foo (); is processed into x Obj; obj.x (...); bingo !! Really stick, C pays attention to the efficiency of complete reflection . This optimization is called ARV (Anonymous Return Value) :) However, what should we do for the former NRV (Named Return Value)? The answer is: There is no way, the only thing that can be used is to expect the compiler to give us some help. If our compiler is power enough, then x foo () {x xx; // process ... returnix;} may be processed: Void foo (x & r) {// ctorr.x (); // Process ...} Here, there is no CTOR and DTOR of Named Object (refer to XX), but as a programmer that should grasp the global, I advise you not to expect it too much. First, it still calls the Default Ctor, which does not exist in ARV. Second, you can't know if the compiler is doing this. After all, for the manufacturer, it does not let you know the details. Again, even if there is such an capability, but only for some simple functions, for actual programming, functions are often complicated, such as functions returned by multiple branches, compilers can only sigh. Also, in the beginning of the function, it is not the act of the object, but it is not authentic C style, C has always advocated "only if it is necessary to use", the real C programmer should keep this. Finally, from the history of C compiler, in the optimization process, anonymous objects are easier than named objects, you have to make full use of it. Answer: For such a simple function, if your compiler supports NRV optimization, the result is the same, otherwise. . . ARV optimization is always supported. Is there any shortcomings in using ARV? Maybe, after all, you have to write a pile of CTOR for special purpose.

转载请注明原文地址:https://www.9cbs.com/read-5503.html

New Post(0)