c++ - std::move 不适用于 RValue 引用函数
问题描述
在尝试学习 std::move 和 rvalue reference 时,我遇到了以下问题:
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> vecNumbers;
vecNumbers.push_back(10);
vecNumbers.push_back(20);
foo(std::move(vecNumbers));
std::cout<<"After Move \n";
std::cout<<"size:"<<vecNumbers.size()<<"\n";
return 0;
}
void foo( std::vector<int> &&value)
{
std::cout<<"size in Function:"<<value.size()<<"\n";
}
输出
size in Function:2
After Move
size:2
在向量上调用move后,我期望大小为 0,但在这里它仅作为参考移动。有人可以解释一下这里发生了什么。
解决方案
std::move
仅转换为 Rvalue 引用。
foo
将 Rvalue ref 设为vector<int>
。由move(vecNumbers)
你得到vector<int>&&
。在里面foo
你只需访问vecNumbers
在main
. 您没有执行任何更改此向量内容的操作。
如果您真的想移动(窃取)内容,vecNumbers
则必须调用移动构造函数或移动赋值运算符。在里面foo
你可以这样做:
void foo( std::vector<int>&& value)
{
std::vector<int> v1{std::move(value)}; // invoke move ctor which steals content of value
std::cout<<"size in Function:"<<value.size()<<"\n";
}
或者您可以将 foo 的签名更改为:
void foo(std::vector<int> value) {
}
那么当你打电话时
foo(std::move(vecNumbers))
move 的构造函数vector<T>
被调用,它移动vecNumbers
到value
里面foo
。
推荐阅读
- rest - Zendesk API 今天得到票解决
- php - 如何将类添加到大于计数的对象?
- security - Magento 1.9 网站未在客户注册表单上生成验证码
- firebase - Vue Webpack:上传到共享主机 url 刷新后返回 404 Not Found
- vba - VBA - 对引用 MergeArea 的单元格进行排序
- c - 使用 c 从计算机读取和打印文本文件
- r - 用两行数据完成单个箱线图,比较正负
- javascript - 试图绕过 Dart 中的闭包
- c++ - 从 C++ 服务器获取 HTTP
- django - 将数据生产者作为工作人员集成到 Django Channels 2.x