Search code examples
c++etl

Move on statically allocated containers benefit


I am not using any heap allocation in my code, any benefit of using move semantics?

Should I be even move-ing anything?

template <typename TIterator1, typename TIterator2>
constexpr TIterator2 move(TIterator1 sb, TIterator1 se, TIterator2 db)
{
    while (sb != se)
    {
        *db =  std::move(*sb); // move instead of copy
        ++db;
        ++sb;
    }

    return db;
}

Not sure how move semantics work on static memory, as all I keep seeing is that its good for moving big heap objects.

Is there a way to check if copy or move is used?


Solution

  • Should I be even move-ing anything?

    You don't need to std::move things that you know don't benefit from moves, like ints. There is however no downside to "overusing" move in cases like your example.

    Templates should use std::move (or std::forward), because they don't know whether they are being used for things that benefit from, or require, moves.

    Is there a way to check if copy or move is used?

    You can write a type that logs when it is moved or copied.

    struct ObserveCopyMove
    {
        ObserveCopyMove() { std::cout << "Default Construct"; }
        ObserveCopyMove(const ObserveCopyMove &) { std::cout << "Copy Construct"; }
        ObserveCopyMove(ObserveCopyMove &&) { std::cout << "Move Construct"; }
        ObserveCopyMove& operator=(const ObserveCopyMove &) { std::cout << "Copy Assign"; return *this; }
        ObserveCopyMove& operator=(ObserveCopyMove &&) { std::cout << "Move Assign"; return *this; }
    };