1

Here is my source code:

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

class Copy {
public:

    Copy() {
        cout << "Constructor called" << endl;
    };

    Copy(const Copy& copy) {
        cout << "Copy constructor called" << endl;
    }

    Copy& operator=(Copy copy) {
        cout << "Copy-Assign constructor called" << endl;
        return *this;
    }

    Copy(Copy &&copy) noexcept {
        cout << "Move constructor called" << endl;
    }

    Copy& operator=(Copy &&copy) noexcept {
        cout << "Move-Assign constructor called" << endl;
        return *this;
    }

    ~Copy() {
        cout << "Destructor called" << endl;
    }
};

Copy TestCopy() {
    Copy cop;
    return cop;
}

vector<Copy> TestCopyVector() {
    vector<Copy> copyVector = vector<Copy>{Copy()};
    return copyVector;
}

int main()
{
    Copy cop = TestCopy();
    //TestCopy();
    //vector<Copy> copyVector = TestCopyVector();

    return 0;
}

In My understanding the line

Copy cop = TestCopy();

Should call Copy's move-assignment. While the output is like bellow:

$ ./test 
Constructor called
Destructor called

Could you anybody help explain this? Thanks.

sunkehappy
  • 8,970
  • 5
  • 44
  • 65
  • 1
    `Copy cop = TestCopy();` will never call move assignment anyway - there's no assignment in this line. In the absence of elision it would call the move constructor. – T.C. Feb 26 '15 at 01:56

1 Answers1

1

It's called RVO (Return value optimization) and it's a well know optimization the compiler is allowed to make in similar situations.

Shoe
  • 74,840
  • 36
  • 166
  • 272