c++ - 当函数参数采用右值引用时,为什么这里不调用移动构造函数?
问题描述
在我看来,这些是该程序应该发生的事情
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;
}
这是为什么 ?
解决方案
推荐阅读
- php - laravel/php 的 Docusign 实现
- java - 无法使用 spring-boot-starter-parent (2.3.0) 运行 spring boot 应用程序
- php - 在 Laravel 7 中计算具有相同模型关系的孩子
- powershell - SSRS / PowerBI 报表服务器 - 通过 Powershell 更新 RDL 中的超链接
- asp.net - 使用配置生成器时未找到 providerName
- javascript - Firebase 集合
- python - 我无法从我的 Button 获得回报 - Python Tkinter
- css - 如何创建具有边界半径的均匀间隔的分隔轮廓?
- javascript - 我是否应该在我的前端网站代码(通过 Firebase 托管)中包含我的 NodeJS/Express 服务器代码(托管在 Heroku 上)?
- git - 如何查看从我的 repo 模板 (GitHub) 创建了多少 repos