移动语义和基元类型

Move semantics and primitive types

本文关键字:类型 语义 移动      更新时间:2023-10-16

示例代码

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. 由于对基元类型的移动操作只是一个副本,我可以假设v1将保持不变吗?或者即使使用基元类型,状态也未指定吗?

  2. 我假设基元类型没有移动语义的原因是因为复制同样快,甚至更快,这是正确的吗?

  1. 不,如果你想假设这一点,你应该复制,而不是移动。

  2. 移动会使源对象处于有效但未指定的状态。基元类型do表现出移动语义。源对象保持不变这一事实表明复制是实现移动的最快方法。