在这个公认的假设示例中,正如预期的那样,在语句结束时销毁了X
类型的右值。但是,仍然可以通过非const引用'x'访问被破坏的对象。这是合法的C ++吗?如果是,结果是否未定义或未指定?编译器不应该在这里发出警告吗?我在g ++ 4.8.1上测试了这个。编译器没有发出错误或警告(flags -pedantic和-Wall)。
#include <iostream>
using namespace std;
struct X
{
int i;
X () { cout << "X ctor this address: " << this << endl; }
~X () { cout << "X dtor this address: " << this << endl; }
X & ref() { cout << "X ref this address: " << this << " i = " << i << endl; return *this; }
int & get () { cout << "X get this address: " << this << " i = " << i << endl; return i; }
void print () { cout << "X print this address: " << this << " i = " << i << endl; }
};
int main()
{
X & x = X().ref();
x.get() = 1234;
x.print();
}
以下是输出:
X ctor this address: 0x7fff4f38ace0
X ref this address: 0x7fff4f38ace0 i = 0
X dtor this address: 0x7fff4f38ace0
X get this address: 0x7fff4f38ace0 i = 0
X print this address: 0x7fff4f38ace0 i = 1234
答案 0 :(得分:3)
它显然是UB,编译器不需要诊断它。
在这个假设的情况下,我认为它可能,但一般情况下并不是这样,因此实现这样一个功能的目的不大。
答案 1 :(得分:1)
未定义的行为。
为了便于解释,我将使用指针代替引用。 (它们几乎相同。)
X *X::ptr() { return this; }
X *pf = X().ptr();
pf->print();
- 构建临时对象。
- 调用
ptr()
,并将临时对象的地址分配给pf
。- 临时对象被破坏。因此,
pf
无效。- 使用无效指针
致电ptr
醇>