Forbid rvalue binding via constructor to member const reference

我与影子孤独终老i 提交于 2019-12-20 03:24:11

问题


I am working on a matrix view class, of which constructor takes a matrix as a parameter and binds it to a const reference member. I would very much like to avoid binding rvalues, since they don't bind via a constructor parameter, and we end up with a dangling reference. I came up with the following (simplified code):

struct Foo{};

class X
{
    const Foo& _foo;
public:    
    X(const Foo&&) = delete;       // prevents rvalue binding
    X(const Foo& foo): _foo(foo){} // lvalue is OK
};

Foo get_Foo()
{
    return {};
}

const Foo get_const_Foo()
{
    return {};
}

Foo& get_lvalue_Foo()
{
    static Foo foo;
    return foo;
}

int main() 
{
//  X x1{get_Foo()};        // does not compile, use of deleted function
//  X x2{get_const_Foo()};  // does not compile, use of deleted function
    X x3{get_lvalue_Foo()}; // this should be OK
}

Basically I delete the constructor that takes const Foo&& as a parameter. Note that I need the const since otherwise someone may return const Foo from a function, and in that case it will bind to the const Foo& constructor.

Question:

Is this the correct paradigm of disable rvalue binding? Am I missing something?

来源:https://stackoverflow.com/questions/33244951/forbid-rvalue-binding-via-constructor-to-member-const-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!