Move semantics and primitive types

左心房为你撑大大i 提交于 2019-12-09 15:34:48

问题


Example code:

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);
}

Output:

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

Questions

  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?

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

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



来源:https://stackoverflow.com/questions/9987298/move-semantics-and-primitive-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!