【问题标题】:Calling a virtual function through a member-access expression通过成员访问表达式调用虚函数
【发布时间】:2015-06-17 04:36:56
【问题描述】:

我遇到了以下规则N4296::12.7/4 [class.cdtor]

如果虚函数调用使用显式类成员访问 (5.2.5) 和对象表达式是指 x 的完整对象 或该对象的基类子对象之一,但不是 x 或其之一 基类子对象,行为未定义。

这是什么意思?你不能用一个例子来解释它吗?这对我来说有点难以想象。

【问题讨论】:

  • 那句话后面不是有例子吗?
  • 其实你不是在十个月前问过pretty much the same question吗?
  • @T.C.其实忘记了。我想知道你是怎么记住的……

标签: c++ base-class


【解决方案1】:

如果你还想知道,这是指当你在基类的析构函数中时,你指的是整个对象中已经被销毁的东西。一个例子:

struct Derived;

struct Base {
    Derived &der;
    Base(Derived &d): der(d) {}
    ~Base();
};

struct Derived: Base {
    int value;
    Derived(): Base(*this) {}
};

#include <iostream>

Base::~Base() {
    std::cout <<
        der.value // this is the undefined behavior! der.value is *gone*
        << std::endl;
}

AFAIK,除了在Base 的析构函数中访问der.value 之外,该代码中的所有内容都是合法的,因为当您销毁Base 时,您已经销毁了Derived,您在der 中保留了一个引用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多