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 for RBV and NRBV correct as indicated in the
comments? - Is it mandatory to have an accessible copy ctor defined though it
is not called during RVO? -
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.
1 Answer