从类返回可移动成员变量

问题描述 投票:0回答:1
class foo{
public:
    bar steal_the_moveable_object();
private:
    bar moveable_object;
};

main(){
    foo f;
    auto moved_object= f.steal_the_moveable_object();
}

如何实现

steal_the_movebale_object
moveable_object
移至
moved_object

c++ c++11 move-semantics
1个回答
7
投票

您可以直接在返回语句中移动成员:

class foo
{
public:
    bar steal_the_moveable_object()
    {
        return std::move(moveable_object);
    }
private:
    bar moveable_object;
};

请注意,这可能不是一个好主意。考虑使用以下内容,以便只能通过右值调用成员函数:

class foo
{
public:
    bar steal_the_moveable_object() && // add '&&' here
    {
        return std::move(moveable_object);
    }
private:
    bar moveable_object;
};

int main()
{
    foo f;
    //auto x = f.steal_the_moveable_object(); // Compiler error
    auto y = std::move(f).steal_the_moveable_object();

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.