Objects and ctors copies created without RVO in C ++

I am new to C ++. Please consider the following code:

class foo { int f; public: foo(int f1=0) : f(f1) { cout<<"In conversion ctor\n"; } foo(const foo & rhs) : f(rhs.f) { cout<<" In copy ctor\n"; } foo& operator=(const foo & that) { f=that.f; cout<<"In = optor\n"; return *this; } }; foo rbv() { foo obj(9); return obj; //named return by value [def. 1] } foo caller() { return rbv(); // return by value [def. 2] } int main(void) { foo box=caller(); return 0; } 
  • Are the definitions correct for RBV and NRBV, as indicated in the Comment?
  • Is it mandatory to have an accessible copy of ctor defined, although it is not called during RVO?
  • No RVO in code blocks

      foo rbv() { foo obj(9); return obj; } foo ret= rbv(); 

Are the following steps performed correctly when creating a 'ret'

(1) a temporary (say, obj_temp) is created using copy ctor from obj, the stack of the object "obj" is destroyed,

(2) ret - a copy built from obj_temp, obj_temp destroyed later;

which implies the presence of three objects: obj ',' obj_temp 'and' ret 'and two instances of ctors.

+4
source share
2 answers
  • Looks like me.
  • You must have the available copy constructor installed if you are going to copy objects. Even if copying can be optimized.
  • This sounds right to me, although accurate sequencing can be implemented. You'll have to
0
source

Are the definitions for RBV and NRBV correct as indicated in the comments?

These are RVO and NRVO (Return Value Optimization and Name Value Optimization)

Is it mandatory to have an accessible copy of ctor defined, although it is not called during RVO?

Necessarily, the compiler must make sure that the constructors are available, if they are not, the compiler must cause an error and not compile.

No RVO in code blocks

 foo rbv() { foo obj(9); return obj; } foo ret = rbv(); 

In this code, based on it, the following operations will be required: A constructor that takes an int inside foo to create obj . Copy the construct in the returned expression to the inverse of time $tmp1 , copy the construction of ret to the place of the call from the temporary. Now the compiler can move away from two copies by placing the return value (in accordance with the calling convention) on top of ret , therefore $tmp1 and ret are the same memory cells and by building obj from above from the same place in memory, so at the end all three objects can be a single object, and copies should not be executed.

+5
source

All Articles