CKTIS / C++
std::move_backward — moving a range from the end
std::move_backward assigns range elements from last to first while preserving their order in the destination. It supports safely shifting an overlapping range to the right.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <algorithm>
template<class BidirectionalIterator1, class BidirectionalIterator2>
constexpr BidirectionalIterator2 move_backward(
BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result);std::move_backward, declared in <algorithm>, move-assigns elements from [first, last) into a range ending immediately before result. For N elements, the destination is [result - N, result). Processing backward does not reverse element order.
Both iterator types must be bidirectional, and destination elements must already exist and support move assignment. The algorithm does not grow a container. It performs exactly N assignments and returns the beginning of the destination range. The notation result - N describes a position; it does not require random-access iterators.
Overlap warning: result must not belong to (first, last]; violating this precondition causes undefined behavior. For overlapping ranges, use this algorithm to shift right and the three-argument std::move to shift left. The one-argument std::move is a cast enabling moves, not a range algorithm.
The example shifts three integers two positions right. Move assignment for int preserves the source value, making the result deterministic. Do not assume that behavior for arbitrary class types.
Examples
#include <algorithm>
#include <iostream>
int main() {
int values[] = {1, 2, 3, 0, 0};
auto first_moved = std::move_backward(values, values + 3, values + 5);
std::cout << "start: " << (first_moved - values) << '\n';
for (int i = 0; i < 5; ++i) {
if (i != 0) std::cout << ' ';
std::cout << values[i];
}
std::cout << '\n';
}
Result
start: 2 1 2 1 2 3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.