从非本地返回右值引用 [英] Returning an rvalue reference from a nonlocal

查看:146
本文介绍了从非本地返回右值引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类被查询一个内部状态对象:

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());
    }
};

这是适当使用 std :: move ?我可以保证 getState 只会在每次调用 process 时调用一次,但由于这个特定系统的设计我不能只是从进程返回 newState 。 Stack Overflow和其他地方的许多其他答案说,最好只是返回对象,因为编译器会移动它或RVO它,如果它可以反正,但那些都在这种情况下,返回的对象是本地的函数。

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.

我不一定需要状态对象在一个unique_ptr后面,但这似乎是最简单的方法来管理新的状态对象。我的实际实现有一个指针直接传递到unique_ptr在结尾。

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.

推荐答案

原来的演示代码是buggy- unique_ptr从不释放指针。答案包括将移动到局部函数空间,然后正常返回。

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.

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;
    }
};

这篇关于从非本地返回右值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆