Understanding and Using std::move_backward Correctly in C++

2025-09-04

std::move_backward is an algorithm in the C++ Standard Library that moves a range of elements to a new location. The key thing is that it does this in reverse order, from the last element to the first. This backward approach is crucial because it helps avoid overwriting elements in the source range when the source and destination ranges overlap. It's often used for things like inserting an element into a sorted array without having to reallocate the whole thing.

The basic syntax is

std::move_backward(first, last, d_last);

first and last
Define the source range you want to move (inclusive of first, exclusive of last).

d_last
Points to one past the end of the destination range.

This is the most common mistake. People often think d_last is the beginning of the destination range, but it's actually the end of the destination range. It's an output iterator to which the last element of the source range will be moved.

Common Mistake

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {10, 20, 30, 40, 50};
    
    // We want to shift elements 20, 30, and 40 to the right by one
    // We'll move them to a new range starting at the next position
    
    // INCORRECT: using the beginning of the destination range
    std::move_backward(numbers.begin() + 1, numbers.begin() + 4, numbers.begin() + 2); 
    
    // The last element (40) is moved to position 2, but the rest is chaos!
    // The function expects the *end* of the destination.
    
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    // Expected Output: 10 20 20 30 40 (or something similar, but wrong)
    // Actual Output:   10 30 40 40 50 (Undefined behavior, since we're overwriting a source element with an uninitialized value)
    
    return 0;
}

The Correct Approach

The destination range should be calculated based on the source range's length. Since the source has 3 elements (20, 30, 40), the destination range must also have a size of 3. If we want to move them one spot to the right, the destination's end should be numbers.begin() + 5.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {10, 20, 30, 40, 50};
    
    // Move elements from index 1 to 4 (20, 30, 40)
    // to a new position, shifted right by one.
    // The new end position should be `numbers.begin() + 4 + 1`.
    
    std::move_backward(numbers.begin() + 1, numbers.begin() + 4, numbers.begin() + 5); 
    
    // Now, the elements at index 1, 2, and 3 are moved to 2, 3, and 4.
    // 20 is moved to index 2, 30 to 3, and 40 to 4.
    
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    // Correct Output: 10 20 20 30 40
    
    return 0;
}

Wait, the output is 10 20 20 30 40. Why is the second 20 there? std::move_backward doesn't erase the source elements; it just moves their values. The original 20 at index 1 is now a moved-from object. If you were doing an insertion, you'd then place the new element at the now-vacant spot (index 1).

std::move_backward is specifically designed for cases where the destination range overlaps with the source range. However, if the destination is before the source and they overlap, you should use std::move instead!

When to use std::move
If you are shifting elements to the left and they overlap, std::move works perfectly because it moves from front to back, avoiding overwriting.

When not to use std::move_backward
Using std::move_backward for a leftward shift on an overlapping range will cause you to overwrite elements before they are moved, leading to data loss or corruption.

Sometimes, std::move_backward isn't the best tool for the job, or there are simpler alternatives.

As mentioned, if your destination is to the left of your source and they overlap, use std::move. It's the forward-moving equivalent.

Example
Shifting elements left

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {10, 20, 30, 40, 50};
    
    // We want to shift elements from index 2 to 5 (30, 40, 50)
    // to a new position, shifted left by one, starting at index 1.
    // The source range is [numbers.begin() + 2, numbers.end())
    // The destination is numbers.begin() + 1
    
    std::move(numbers.begin() + 2, numbers.end(), numbers.begin() + 1);
    
    // The source element at index 2 (30) is moved to index 1.
    // The source element at index 3 (40) is moved to index 2.
    // ...and so on.
    
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    // Output: 10 30 40 50 50
    
    return 0;
}

Notice the last 50 is still there. Like std::move_backward, std::move doesn't erase the source; it simply moves the values.

For inserting a single element into a sorted range, std::move_backward is a great low-level tool, but there are often higher-level functions that can do the same job more safely and with less code.

Using std::rotate std::rotate is very useful for circular shifts. You can use it to "make a hole" for a new element. It's often more intuitive than manually calculating iterators for move_backward.

Example
Inserting an element with std::rotate

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {10, 20, 40, 50};
    int new_value = 30;
    
    // Find the insertion point (where 30 should go)
    auto it = std::lower_bound(numbers.begin(), numbers.end(), new_value);
    
    // Add the new element at the end of the vector
    numbers.push_back(new_value);
    
    // Rotate the new element into its correct position
    std::rotate(it, numbers.end() - 1, numbers.end());
    
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    // Output: 10 20 30 40 50
    
    return 0;
}

Using std::insert If you don't need the low-level efficiency of std::move_backward and are working with a std::vector or std::deque, the container's own insert method is the simplest and safest way. It handles all the moving for you.

Example
Inserting an element with std::insert

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {10, 20, 40, 50};
    int new_value = 30;
    
    // Find the insertion point
    auto it = std::lower_bound(numbers.begin(), numbers.end(), new_value);
    
    // Use the vector's insert method
    numbers.insert(it, new_value);
    
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    // Output: 10 20 30 40 50
    
    return 0;
}

std::move_backward is for moving elements when the destination range overlaps and is to the right of the source.

The d_last iterator is the end of the destination, not the beginning.

For overlapping ranges where the destination is to the left, use std::move.


cpp



Concurrency in C++: Avoiding Common std::shared_future::get Issues

In C++, std::shared_future is a powerful tool for asynchronous programming, allowing multiple threads to wait for and access the result of an asynchronous operation


Mastering std::filesystem::hash_value: Pitfalls and Canonical Hashing

Here's a friendly breakdown of the function, common pitfalls, and solid alternatives.The function std::filesystem::hash_value(const std::filesystem::path& p) calculates a hash value for a std::filesystem::path object


Common Issues and Alternatives for std::isalnum(std::locale) in C++

When you use std::isalnum with a std::locale object, the most frequent pitfall is misunderstanding how locales work. Many developers assume a locale will behave as expected without proper setup



C++ Filesystem: A Guide to directory_entry Assignment and Error Handling

One of the main issues people run into with the assignment operator (operator=) for std::filesystem::directory_entry is handling exceptions


C++ std::identity: Common Issues and Alternatives

At its core, std::identity is a function object that takes a single argument and returns that same argument by value. Its primary purpose is to act as a placeholder in generic programming contexts


Fixing the C++ Compile Error for operator<< (std::filesystem::directory_entry)

The most frequent issue people run into is a compilation error when trying to directly print a std::filesystem::directory_entry object


Exploring C++ std::regex_traits::translate: Common Pitfalls and Solutions

In short, std::regex_traits::translate is a function that's part of the std::regex_traits class. This class is used by the C++ <regex> library to customize how regular expressions behave


Efficient C++ String Comparison: Why to Skip the Raw compare()

Let's dive into some common pitfalls and great alternatives in a friendly way!The compare() method performs a lexicographical comparison of the sequence of characters currently referenced by the string_view against another string or view


Troubleshooting C++ std::chrono::year and its Alternatives

One of the most frequent problems people run into with std::chrono::year is invalid values. The std::chrono::year type has a valid range


Common Issues and Alternatives for C++ std::chrono::local_time_format

One of the most frequent problems is trying to format a std::chrono::local_time with a timezone that doesn't match the system's local timezone