jeudi 8 août 2019

Why is the move constructor not invoked here when the function parameter takes an rvalue reference?

In my mind these are the things that should be happening to this program
1. Int i(i) -> Create a new Int object, call the copy ctor.
2. print(std::move(i)) -> Create an Rvalue reference out of i and then assign it to a, and in doing so call the move ctor. 3. cout "print 1".
4. cout "main func -1", because the move ctor pillaged its resource.

So my expectation of the output is:

ctor
move ctor
print 1
main func -1

But, the move ctor is never called. And this is the output that is actually seen:

ctor
print 2
main func 2

class Int {  
 public:  
  Int(int i) : i_(i) { std::cout << "ctor" << std::endl; }  
  Int(const Int& other) {  
    std::cout << "copy ctor " << std::endl;  
    i_ = other.i_;  
  }  

  Int(Int&& other) {  
    std::cout << "move ctor " << std::endl;  
    i_ = other.i_;  
    // Pillage the other's resource by setting its value to -1.
    other.i_ = -1;   
  }  
  int i_;   
};  

void print(Int&& a) { std::cout << "print " << a.i_ << std::endl; }  

int main() {  
  Int i(1);  
  print(std::move(i));  
  std::cout << "main func " << i.i_ << std::endl;  
}  

Why is that ?

Aucun commentaire:

Enregistrer un commentaire