1

the obj should have been destroyed at the end of function call 'f', the object returned should have been a new object. I should have got the "Destroying" message twice.

#include <iostream>
using namespace std;

class c{
    int i;
public:
    ~c(){cout<<"Destroying"<<endl;}
    c(){cout<<"Constructing"<<endl;}
    c(const c &a){cout<<"Copy Constructing"<<endl;}
    int get_i(){cout<<i<<endl;return i;}
    void set_i(int i){this->i=i;}
};

c f(){
    c obj;
    obj.set_i(1);
    return obj;
}
int main() {
    f().get_i();
    return 0;
}

1 Answers1

1

This is named return value optimization (NRVO). It is an optimization to remove unnecessary copies of objects. The object obj is being constructed directly in the return value of the function.

The elision of copies is explicitly allowed in a few circumstances, including:

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324