How were move semantics addressed before C++11?

前端 未结 1 2086
攒了一身酷
攒了一身酷 2021-02-10 06:03

I\'ve been reading up on move semantics lately and how it was introduced into C++11. The main gist is that programs could become more efficient by creating objects by \'stealing

相关标签:
1条回答
  • 2021-02-10 06:35

    The main way this was done was via std::swap. std::swap could be overloaded/specialized for types where it could be executed more efficiently than the default "swap via a temporary variable" to instead perform a shallow swap.

    Often data types would provide a swap() member function that could be used by this overload to access the private internals of the data type. (For example; see std::vector::swap)

    For example; to "move" an element into a vector, the following code could be used:

    class MyListOfVectors {
        private:
        //using `std::vector<int>` as an example of a "movable" type.
        std::vector<std::vector<int>> list;
        public:
        void emplace_back(std::vector<int> &n) {
            using std::swap;
            list.push_back(std::vector<int>());
            swap(list.back(), n);
            //(possibly add something to rollback the `push`
            // in case swap fails; to provide the strong
            // exception guarantee)
        }
    };
    

    To return an element via "move", the following code could be used:

    std::vector<int> MyListOfVectors::pop_back() {
        using std::swap;
        std::vector<int> r;
        swap(list.back(), r);
        list.pop_back();
        return r; //Trust in copy elision to avoid any actual copies.
    }
    

    I don't have a reference for this, but I believe standard algorithms were allowed/encouraged to use std::swap for this purpose.

    Also, if you were feeling like you wanted to do things the C++11 way, you could also use boost::move, which provides an emulation of the C++11 move semantics in C++03 (though it technically violates strict aliasing and so has undefined behavior).

    0 讨论(0)
提交回复
热议问题