Is it a premature optimization to use std::move()?

I’m not sure how the compiler would optimize away the copy (if at all) without the std::move().

Only a very clever compiler could optimise that away, so if the copy could be expensive (e.g. a very long string) then it is better to move it.

Without the move the code is effectively a sequences of calls to:

strlen  // count "Hello World"
malloc  // allocate memory for string var
strcpy  // copy data into var
malloc  // re-allocate vector
free    // deallocate old vector
malloc  // allocate new string
strcpy  // copy from var to new string
free    // destroy var

With the move it becomes:

strlen  // count "Hello World"
malloc  // allocate memory for string var
strcpy  // copy data into var
malloc  // re-allocate vector
free    // deallocate old vector

In theory a smart compiler could do that transformation automatically, but for the compiler to see through all the layers of abstraction introduced by the constructors and destructor and the vector member functions is quite difficult, so proving that the code could be transformed to remove a malloc and free is complicated.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)