有一个限制:
Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see 12.7. Otherwise, such a glvalue refers to allocated storage (3.7.4.2), and using the properties of the glvalue that do not depend on its value is well-defined. The program has undefined behavior if:
[...]
— the glvalue is bound to a reference to a virtual base class (8.5.3),
[...]
glvalue 绑定(bind)到虚基类的引用并同时引用原始对象怎么可能呢?你能举个例子吗?
最佳答案
你读错了那句话。对于指向生命周期结束的对象的指针,您引用的要点的直接模拟是 (§3.8 [basic.life]/p5):
- the pointer is implicitly converted (4.10) to a pointer to a virtual base class
所以它在谈论这样的事情:
struct A { };
struct B : virtual A { ~B() {} };
int main() {
B* pb = new B;
B& rb = *pb;
A& ra1 = rb;
pb->~B(); // ends lifetime of *pb
&rb; // OK
A& ra2 = rb; // Undefined behavior. The glvalue rb, referring to an object whose lifetime
// has ended, is bound to a reference to its virtual base class A
A* pa = pb; // Equally undefined
}
关于c++ - Glvalue 引用一个基类子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25708892/