【问题标题】:Move semantics and primitive types移动语义和原始类型
【发布时间】:2012-04-03 04:50:17
【问题描述】:

示例代码

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. 我假设原始类型没有移动语义的原因是因为复制速度一样快甚至更快,这是正确的吗?

【问题讨论】:

    标签: c++ c++11 primitive move-semantics


    【解决方案1】:
    1. 不,如果您希望能够假设这一点,您应该复制而不是移动。

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

    【讨论】:

    • “有效但未指定的状态”规则仅适用于标准库类型 ([lib.types.movedfrom])。 “移动”原始类型由核心语言规则控制,对于此类类型,移动就是一个副本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多