3

Possible Duplicate:
What are copy elision and return value optimization?

I have the following program:

#include <iostream>

using namespace std;

class Pointt {
public:
    int x;
    int y;

    Pointt() {
        x = 0;
        y = 0;
        cout << "def constructor called" << endl;
    }

    Pointt(int x, int y) {
        this->x = x;
        this->y = y;
        cout << "constructor called" << endl;
    }

    Pointt(const Pointt& p) {
        this->x = p.x;
        this->y = p.y;
        cout << "copy const called" << endl;
    }

    Pointt& operator=(const Pointt& p) {
        this->x = p.x;
        this->y = p.y;
        cout << "op= called" << endl;
        return *this;
    }
};

Pointt func() {
    cout << "func: 1" << endl;
    Pointt p(1,2);
    cout << "func: 2" << endl;
    return p;
}


int main() {
    cout << "main:1" << endl;
    Pointt k = func();
    cout << "main:2" << endl;
    cout << k.x << " " << k.y << endl;
    return 0;
}

The output I expect is the following:

main:1
func: 1
constructor called
func: 2
copy const called
op= called
main:2
1 2

But I get the following:

main:1
func: 1
constructor called
func: 2
main:2
1 2

The question is: why doesn't returning an object from func to main call my copy constructor?

Community
  • 1
  • 1
sedran
  • 3,498
  • 3
  • 23
  • 39
  • 2
    I understand why you expect the copy constructor to be called, but you should not expect the assignment operator to be called. When "`=`" is used in an initialization, is not actually the assignment operator, it is copy initialization(which is optimized away in this case). Without optimizations, there would be 2 calls to the copy constructor. – Benjamin Lindley Nov 28 '12 at 23:50

1 Answers1

5

This is due to Return Value Optimization. This is one of the few instances where C++ is allowed to change program behavior for an optimization.

Cogwheel
  • 22,781
  • 4
  • 49
  • 67