c++ - 为什么 std::move( arg ) 改变 arg 参数?

标签 c++ c++11 move-semantics

有代码

string one = "one";
string two{ one };
string three{ move(one)};
cout << one  << endl;

这会打印“”。这是因为调用了字符串三的 move 构造函数并窃取了其参数值。但是,变量一怎么会被修改呢?

当我们传递 move(one) 时,会返回右值。并且 move 构造函数从该右值窃取资源,变量一不作为引用或指针传递到那里。那么为什么会发生这样的行为呢?

感谢您的解答

最佳答案

std::move() 实际上并没有改变它的参数

...但它确实让代码获取其输出“蚕食”参数。因此,您的 two 字符串会占用 one 的缓冲区,将其留空。

您还可以阅读this detailed explanation关于网站上的 std::move() (回答问题 "what is std::move() and when should it be used" )。

关于c++ - 为什么 std::move( arg ) 改变 arg 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47114551/

相关文章:

html - 使用 Visual Studio 获取 URL 链接的 HTML

c# - 编译 eAccelerator 解码 PHP 编码文件

c++ - 在 Linux 上使用 CMake 构建 gRPC C++

c++ - 带有 move 语义的源函数和汇函数的签名

c++ - 在 C++ 中将具有 unique_ptr 的对象插入 vector

c++11 - C++ 允许将数据移出类成员的最佳方法是什么(std::move 语法)

C++11 局部静态值不作为模板参数

c++ - C++11 中具有对齐元素的 std::array 类型

c++ - 方法编译时断言;还是行不通

c++ - 为什么 std::bind 不能与 std::filesystem::path 和 std::ostream 一起工作?