开发者

Objects and copy ctors 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; 
 }
  1. Are the definitions for RBV and NRBV correct as indicated in the comments?
  2. Is it mandatory to have an accessible copy ctor defined though it is not called during RVO?
  3. Without RVO, in the code blocks

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

Are the following steps correct in creation of 'ret'

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

(2) ret is copy constructed from obj_temp, obj_temp destroyed later;

which implies there are three objects, 'obj' , 'obj_temp' and 'ret' and two copy ctors involved.


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

They are RVO and NRVO (Return Value Optimization and Named Return Value Optimization)

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

It is mandatory, the compiler has to verify that the constructors are accessible, if they are not, the compiler must trigger an error and fail to compile.

Without RVO, in the code blocks

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

The code, as it stands would require the following operations: Constructor taking an int inside foo to create obj. Copy construction in the return statement to the return temporary $tmp1, copy construction of ret at the call place from the temporary. Now, the compiler can elide the two copies by placing the return value (according to the call convention) on top of ret, so $tmp1 and ret are the same memory location, and by constructing obj on top of the same memory location, so at the end all three objects can be a single object and no copies need to be performed.


  1. Looks right to me.
  2. You have to have an accessible copy constructor defined if you are going to copy objects. Even if the copy can be optimized away.
  3. That sounds right to me, though the precise ordering might be implementation defined. You would have to
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜