0

I am learning c++11 copy and move semantics, and have written some experimental code to verify my thoughts, but the output really baffled me.

class CP{
public:
CP(int input):val(input){
    cout << "constructor" << endl;
}

CP(const CP& rhs){
    //initialize 'val' using in-class initializer
    cout << "cp constructor" << endl;
}

CP(CP&& rhs) noexcept {
    //initialize 'val using in-class initializer
    cout << "move constructor"<< endl;
}

CP& operator=(CP&& rhs) noexcept{
    cout << "move operator=" << endl;
    return *this;
}

CP& operator=(const CP& rhs){
    cout << "operator=" << endl;
    return *this;

}

~CP(){
    cout << "destructor" << endl;
}
private:
    int val = 0;
};

CP fun()
{
    return CP(42);
}

int main() {
    CP cp1 = fun();
    cout << "---" << endl;
    CP cp2 = std::move(cp1);
    cout << "---move out of scope---" << endl;
    return 0;
}

This code outputs:

constructor
---
move constructor
---move out of scope---
destructor
destructor

What contradict my understandings is the output of the code

CP cp1 = fun(); 

To the best of my knowledge, fun() returns a value of class CP, and thus a rvalue, so the move constructor of class CP should be called to initialize variable cp1. But according to the output, it seems that none of my defined functions are called in the initialization process of the variable cp1.

My question is :

  1. Are my declarations and definitions of class CP's copy control functions correct?

  2. What is wrong with my understanding, and how is cp1 initialized?

Any help would be appreciated, and thanks in advance.

Zhao Chen
  • 143
  • 1
  • 10

0 Answers0