c++ - Glvalue 引用一个基类子对象

标签 c++ lvalue

有一个限制:

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/

相关文章:

c - C编程中,要求L值是语义错误还是语法错误?

c++ - 需要 Meyers Effective C++ Widget 右值实例讲解

c++ - 将右值引用传递给 const 左值引用参数

c++ - 在 C++ Win32 中处理控制台应用程序/DLL 中的消息

c++ - 在 freopen() 之后从标准输入获取输入

c++ - 在 MFC C++ 应用程序中在屏幕上绘制点的最快方法

c - 即使在正确转换后,增加 void 指针所需的左值

c++ - 通过引用传递表达式与通过引用传递变量

c++ - 初始化 C++11 数组的最佳方法,该数组主要是身份映射

c++ - TRegEx::IsMatch 始终为假