gpt4 book ai didi

c++ - 通过成员访问表达式调用虚函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:50:00 25 4
gpt4 key购买 nike

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

If the virtual function call uses an explicit class member access (5.2.5) and the object expression refers to the complete object of x or one of that object’s base class subobjects but not x or one of its base class subobjects, the behavior is undefined.

这是什么意思?你不能举例说明一下吗?对我来说有点难以想象。

最佳答案

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

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 时,您您已经销毁了您在 der

中保留引用的 Derived

关于c++ - 通过成员访问表达式调用虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30882420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com