I wrote an in-place permutation algorithm [an exercise in TAOCP3], where the inner loop is
template<typename T>
void inplace_permute(T *pT, int *P, const int n)
{
// part of the inner loop
pT[j] = std::move(pT[k]);
P[j] = j;
// more logic to update j, k, etc.
}
Here, pT is the array of elements to be sorted, P is the permutation table and n is the number of elements.
Will std::move increase performance if T is a complex type, e.g., a string? Also important, can it be optimized out if T is a primitive type (e.g., an int?)
I’ll sum up your question as:
Basically,
std::movemakes the use of Move Constructor and Move Assignment Operator available.Typically, those are close to a bitwise copy (they are not exactly one), and so the performance is usually related to the
sizeofthe class.Therefore,
std::move(someint)andstd::move(somestring)would have similar performance if they had a similar size, even though one is a built-in and the other a user class.There are some differences though.
To understand, we can illustrate this with an example string implementation:
As you can see, the assignment
pT[j] = std::move(pT[k]);means (semantically):pT[k])pT[k]pT[j]pT[j])The compiler should, more or less, be able to optimize it into:
pT[j]andpT[k]pT[k](just release the storage)pT[k]Or, crudely:
Note: this is a toy implementation, it would be a bit more simple on gcc and much more complex on VC++ as they use different representations of the data.