简体   繁体   English

内置类型是否具有移动语义?

[英]Do built-in types have move semantics?

Consider this code: 考虑以下代码:

#include <iostream>
using namespace std;

void Func(int&& i) {
    ++i;
}

int main() {
    int num = 1234;
    cout << "Before: " << num << endl;
    Func(std::move(num));
    cout << "After: " << num << endl;
}

Its output is: 其输出为:

Before: 1234
After: 1235

Clearly, i is being modified inside Func , as it is bound to parameter i after being "converted" to an r-value reference by std::move . 显然, i正在Func内部进行修改,因为它在通过std::move “转换”为r值引用之后绑定到了参数i

Well, my point: 好吧,我的意思是:

Moving an object means transferring ownership of resources from one object into another. 移动对象意味着将资源所有权从一个对象转移到另一个对象。 However, built-in types holds no resources because they themselves are the resources. 但是,内置类型不保留资源,因为它们本身就是资源。 It makes no sense to transfer the resources they hold. 转移他们持有的资源没有任何意义。 As shown by the example, num 's value is modified. 如示例所示, num的值被修改。 Its resource, its self, is the one being modified. 它的资源,其自身,就是被修改的资源。

Do built-in types have move semantics? 内置类型是否具有移动语义?

Also, Do built-in type objects after it is moved (if it is) a well-defined behavior? 另外,内置类型对象在移动后(如果确实存在)是否定义良好?

And so, is the one shown by the example a well-defined behavior? 因此,该示例所示的行为是否定义明确?

Yes, the behaviour shown in the example is the only behaviour allowed by the standard. 是的,示例中显示的行为是标准所允许的唯一行为。 That is because std::move doesn't move. 这是因为std::move不会移动。 The things that move are move constructors and move assignment operators. 移动的是移动构造函数和移动赋值运算符。

All std::move does is change an lvalue into an xvalue, so that it can bind to rvalue references. 所有std::move所做的就是将一个左值更改为一个xvalue,以便它可以绑定到右值引用。 It does not invoke any constructor or anything else. 它不会调用任何构造函数或其他任何东西。 Changing the value category happens at the type level. 更改值类别发生在类型级别。 Nothing happens at runtime. 在运行时没有任何反应

Rvalue references are still references: they refer to the original object. 右值引用仍然是引用:它们引用原始对象。 The function increments the original integer through the reference given. 该函数通过给定的引用递增原始整数。

If a function takes an argument by reference, no copies nor moves happen: the original object is bound to the reference. 如果函数通过引用接受参数,则不会发生复制或移动:原始对象绑定到引用。

If a function takes an argument by value, then we might have a move. 如果一个函数按值接受参数,那么我们可能会采取行动。

However, fundamental types don't have move constructors. 但是,基本类型没有移动构造函数。 Moves degrade to copies in that case. 在这种情况下,移动降级为副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM