首页 > 解决方案 > 当函数参数采用右值引用时,为什么这里不调用移动构造函数?

问题描述

在我看来,这些是该程序应该发生的事情
1. Int i(i) -> 创建一个新的 Int 对象,调用复制 ctor。
2. print(std::move(i)) -> 从 i 中创建一个 Rvalue 引用,然后将其分配给 a,然后调用 move ctor。3. cout“打印1”。
4. cout "main func -1",因为 move ctor 掠夺了它的资源。

所以我对输出的期望是:

ctor
move ctor
print 1
main func -1

但是,永远不会调用 move ctor。这是实际看到的输出:

ctor
打印 2
主要功能 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;  
}  

这是为什么 ?

标签: c++c++11rvalue-reference

解决方案


推荐阅读