I have read in some others posts that move is unnecessary and even deoptimizes mechanisms like NRVO. But it was in most cases about a local field.
Consider this example:
- A class stores a temporary field after a computation.
- I want to take this field without copying it ("consuming" it).
In this case, is it appropriate to use std::move on return?
Specifically, are these pieces of code equivalent?
The second is more "generic", letting the user decide if the result should be moved or not, and the first one is more strict — any call will consume the result.
Option 1
// Option 1
#include <utility>
template<typename T>
class TemporaryResultHolder
{
public:
void doTask() { result = T(); }
T getResult() { return std::move(result); }
// Or return T&& ?
private:
T result;
};
int main() {
TemporaryResultHolder<int> holder;
holder.doTask();
int res = holder.getResult();
return 0;
}
Option 2
// Option 2
#include <utility>
template<typename T>
class TemporaryResultHolder
{
public:
void doTask() { result = T(); }
T getResult() { return result; }
private:
T result;
};
int main() {
TemporaryResultHolder<int> holder;
holder.doTask();
int res = std::move(holder.getResult());
return 0;
}