移动语义和原始类型

Jes*_*ood 9 c++ primitive move-semantics c++11

示例代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

问题

  1. 由于对原始类型的移动操作只是一个副本,我可以假设v1它将保持不变或者即使使用原始类型也未指定状态吗?

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

CB *_*ley 15

  1. 不,如果你想能够假设你应该复制,而不是移动.

  2. 移动使源对象处于有效但未指定的状态.原始类型确实表现出移动语义.源对象保持不变的事实表明复制是实现移动的最快方式.

  • "有效但未指定的状态"规则仅适用于标准库类型([lib.types.movedfrom])."移动"原始类型由核心语言规则控制,对于这种类型,移动是副本. (2认同)