内置类型有移动语义吗? [英] Do built-in types have move semantics?

查看:269
本文介绍了内置类型有移动语义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑代码:

  #include< iostream> 
using namespace std;

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

int main(){
int num = 1234;
cout<< 之前:<< num<< endl;
Func(std :: move(num));
cout<< 之后:< num<< endl;
}

其输出为:

 之前:1234 
之后:1235

显然, i 正在 Func 内修改,因为它绑定到参数 i



之后,将code转换为r值引用> 好,我的观点:



移动对象意味着将资源的所有权从一个对象转移到另一个对象。但是,内置类型保存没有资源,因为它们自己是资源。转让他们持有的资源是没有意义的。如示例所示,修改 num 的值。



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

此外,在内置类型对象被移动(如果是)之后,是否有明确定义的行为?

解决方案


因此,示例中显示的是一个明确定义的行为?


是的,示例中显示的行为是标准允许的唯一行为。这是因为 std :: move 不移动。移动的东西是移动构造函数和移动赋值运算符。



全部 std :: move 转换为xvalue,以便它可以绑定到右值引用。它不调用任何构造函数或任何其他。更改值类别发生在类型级别。



Rvalue引用仍然是引用:它们引用原始对象。该函数通过给定的引用递增原始整数。



如果函数通过引用接受参数,则不会发生副本或移动:原始对象绑定到引用。



如果函数接受参数的值,那么我们可能有移动。



但是,基本类型没有move构造函数。在这种情况下,移动会降级到副本。


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.

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. 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. 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. 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.

这篇关于内置类型有移动语义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆