0

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 ?

shrinidhisondur
  • 771
  • 1
  • 8
  • 18
  • `void print(Int&& a); print(std::move(i))` nothing here constructs a new object. If you want to get a new instance of `Int`, then declare `void print(Int a);`. – 273K Aug 08 '19 at 17:52
  • `print` receives a reference to the original object. – Ben Voigt Aug 08 '19 at 17:53
  • An rvalue reference still is a reference. As long as you do not construct a value object from... – Aconcagua Aug 08 '19 at 17:58

0 Answers0