我有一个查询内部状态对象的类:
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());
}
};
这是对 std::move
的恰当使用吗? ?我可以保证 getState
每次调用 process
只会被调用一次, 但由于这个特定系统的设计,我不能只返回 newState
来自 process
. Stack Overflow 和其他地方的许多其他答案都说最好只返回对象,因为编译器会 move 它或 RVO 它,如果可以的话,但这些都是在返回的对象是函数本地的情况下.
我不一定需要将状态对象置于 unique_ptr 之后,但这似乎是管理新状态对象的最简单方法。我的实际实现有一个指针在最后直接传输到 unique_ptr。
最佳答案
事实证明,原始演示代码存在错误——unique_ptr 永远不会释放指针。答案涉及 move 到局部函数空间,然后正常返回。
class State {...}; //Has a copy and move constructor
class Processor
{
private:
std::unique_ptr<State> state;
public:
void process(...)
{
State* newState;
... //newState is allocated on the heap somehow
state.reset(newState);
}
State getState()
{
State _state(std::move(*state));
//Optionally: state.reset();
return _state;
}
};
关于c++ - 从非本地返回一个右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14614903/