I have a class that is queried for an internal state object:
class State {...}; //Has a copy and move constructor
class Processor
{
private:
std::unique_ptr<State> state;
public:
void process(...)
{
State newState;
... //create this new state
state.reset(new State(newState));
}
State getState()
{
return std::move(*state.release());
}
};
Is this an appropriate use of std::move? I can guarantee that getState will only be called once per call to process, but because of the design of this particular system I can’t just return newState from process. Many of the other answers on Stack Overflow and elsewhere said that it’s better to just return the object, because the compiler will move it or RVO it if it can anyway, but those were all in the case that the returned object was local to the function.
I don’t necessarily need the state object to be behind a unique_ptr, but that seemed like the easiest way to do manage the new state objects. My actual implementation has a pointer being transferred directly to the unique_ptr at the end.
It turns out that the original demo code is buggy- the unique_ptr never frees the pointer. The answer involves moving onto the local function space and then returning normally.