移动语义和基本类型 [英] Move semantics and primitive types

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

问题描述

示例代码

int main()
{
    std::vector<int> v1{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::cout << "Printing v1" << std::endl;
    print(v1);
    std::vector<int> v2(std::make_move_iterator(v1.begin()),
                         std::make_move_iterator(v1.end()));
    std::cout << "Printing v1" << std::endl;
    print(v1);
    std::cout << "Printing v2" << std::endl;
    print(v2);

    std::vector<std::string> v3{"some", "stuff", "to",
                        "put", "in", "the", "strings"};
    std::cout << "Printing v3" << std::endl;
    print(v3);
    std::vector<std::string> v4(std::make_move_iterator(v3.begin()),
                                 std::make_move_iterator(v3.end()));
    std::cout << "Printing v3" << std::endl;
    print(v3);
    std::cout << "Printing v4" << std::endl;
    print(v4);
}

输出

Printing v1
1 2 3 4 5 6 7 8 9 10
Printing v1
1 2 3 4 5 6 7 8 9 10
Printing v2
1 2 3 4 5 6 7 8 9 10
Printing v3
some stuff to put in the strings
Printing v3

Printing v4
some stuff to put in the strings


  1. 由于对原始类型的移动操作只是一个副本,我可以假设

  1. Since move operations on primitive types is just a copy, can I assume that v1 will be left unchanged or is the state unspecified even with primitive types?

我假设原始类型的原因是什么没有移动语义是因为复制正快,甚至更快,这是正确的吗?

I'm assuming the reason why primitive types don't have move semantics is because copying is just as fast or even faster, is this correct?


推荐答案


  1. 不,如果您想要能够假设您应该复制,不要移动。

  1. No, if you want to be able to assume this you should copy, not move.

移动使源对象处于有效但未指定的状态。基本类型 do 展示移动语义。事实上源对象保持不变意味着复制是实现移动的最快方式。

A move leaves the source object in a valid but unspecified state. Primitive types do exhibit move semantics. The fact that source object is left unchanged is what suggests that copying is the fastest way to implement moving.

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

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