Move semantics vs Copy semantics; And when to use them.

#include <vector>
#include <iostream>

class Semantics
{
public:
    // Pass by value to store a new copy using std::move 
    // (rvalue is moved, lvalue is copied)
    Semantics(std::vector<int> in) : 
        m_v(std::move(in)) 
    {

    }

    std::vector<int> get() const 
    { 
        return m_v; 
    }

    // Pass by reference to modify an `out` parameter: lvalue only
    void append(std::vector<int> &out) 
    { 
        out.insert(out.end(), m_v.begin(), m_v.end()); 
    }

    // Pass by const reference as read-only `in` parameter: lvalue copied, rvalue copied
    void append(const std::vector<int> &in) 
    { 
        m_v.insert(m_v.end(), in.begin(), in.end()); 
    }
private:
    std::vector<int> m_v;
};


int main() 
{
    {
        std::cout << std::endl << 
        "Pass by value to store a new copy using std::move: rvalue is moved" << std::endl;

        Semantics s( std::vector<int> {1,2,3} );
        for(auto i: s.get()) { std::cout << i; }
        std::cout << std::endl;
    }
    {
        std::cout << std::endl << 
        "Pass by value to store a new copy using std::move: lvalue is copied" << std::endl;

        std::vector<int> v{4,5,6};
        Semantics s( v );
        for(auto i: v) { std::cout << i; }
        std::cout << std::endl;
    }
    {
        std::cout << std::endl << 
        "Pass by reference to modify an `out` parameter: lvalue only" << std::endl; 

        Semantics s( std::vector<int> {4,5,6} );
        std::vector<int> v{1,2,3};
        s.append(v);
        for(auto i: v) { std::cout << i; }
        std::cout << std::endl;
    }
    {
        std::cout << std::endl << 
        "Pass by const reference as read-only `in` parameter: rvalue copied" << std::endl;
        Semantics s( std::vector<int> {4,5,6} );
        s.append(std::vector<int> {1,2,3});
        for(auto i: s.get()) { std::cout << i; }

    }
    {
        std::cout << std::endl << 
        "Pass by const reference as read-only `in` parameter: rvalue copied" << std::endl;
        Semantics s( std::vector<int> {4,5,6} );
        const std::vector<int> v{1,2,3};
        s.append(v);
        for(auto i: s.get()) { std::cout << i; }

    }

    return 0;
}

https://godbolt.org/z/85ha4ezrn

Categories: C++

Leave a Reply

Your email address will not be published. Required fields are marked *