我正在研究一个矩阵视图类,其中的构造函数将矩阵作为参数并将其绑定到const
引用成员。我非常想避免绑定右值,因为它们不是通过构造函数参数绑定的,我们最终会得到一个悬空引用。我想出了以下(简化代码):
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
}
基本上我删除了const Foo&&
作为参数的构造函数。请注意,我需要,const
否则有人可能会const Foo
从函数返回,在这种情况下,它将绑定到const Foo&
构造函数。
问题:
这是禁用右值绑定的正确范例吗?我错过了什么吗?