[英]Pointer to rvalue object member variable
This is a very quick question.这是一个非常快速的问题。 I have the following code:我有以下代码:
struct integer {
int x;
int& ref() {
return x;
}
};
//main...
int* l = &integer{4}.ref();
std::cout << *l;
My question is: Isn't &integer{4}.ref()
a rvalue since it is a temporary object?我的问题是: &integer{4}.ref()
不是一个右值,因为它是一个临时对象吗? How can I have a pointer to it?我怎么能有一个指向它的指针? And is it undefined behavior?这是未定义的行为吗?
While integer{4}
is an rvalue, you call ref()
which returns an int&
which is always an lvalue.虽然integer{4}
是一个右值,但您调用ref()
会返回一个int&
,它始终是一个左值。 This allows the code to compile, but you have undefined behavior since you dereference a pointer to an object that no longer exists.这允许代码编译,但由于您取消引用指向不再存在的对象的指针,因此您具有未定义的行为。
To fix this you can provide a ref-qualifer for ref
which only allows it to be called on lvalues.为了解决这个问题,你可以提供一个参考,对于限定符ref
只允许它在左值调用。 That would look like那看起来像
struct integer {
int x;
int& ref() & {
return x;
}
};
and will cause a compiler error if you try to use如果您尝试使用,将导致编译器错误
integer{4}.ref()
since integer{4}
is not an lvalue which ref
now requires.因为integer{4}
不是ref
现在需要的左值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.