copy vs std::move for ints

前端 未结 4 1635
一生所求
一生所求 2020-12-08 14:20
  • What\'s difference between default copy and std::move in that example?
  • After move the object is there any dependence between new and old ones?
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 15:07

    To expand on the other poster's answer, the move-is-a-copy paradigm applies to all data structures composed of POD types (or composed of other types composed of POD types) as well, as in this example:

    struct Foo
    {
        int values[100];
        bool flagA;
        bool flagB;
    };
    
    struct Bar
    {
        Foo foo1;
        Foo foo2;
    };
    
    int main()
    {
        Foo f;
        Foo fCopy = std::move(f);
        Bar b;
        Bar bCopy = std::move(b);
        return 0;
    }
    

    In the case of both Foo and Bar there is no meaningful way to move the data from one to another because both are ultimately aggregates of POD types - none of their data is indirectly owned (points to or references other memory). So in these cases, the move is implemented as a copy and originals (f, b) remain unaltered after the assignments on the std::move() lines.

    Move semantics can only be meaningfully implemented with dynamically allocated memory or unique resources.

提交回复
热议问题