class base {
int a;
protected:
template<class T>
class derived;
public:
base() {}
virtual ~base() {}
virtual void func() {}
static base* maker();
};
template <class T>
class base::derived
: public base
{
public:
derived() {}
virtual ~derived() {}
virtual void func() {
this->~derived(); //<--is this legal?
new (this) derived<int>(); //<--is this legal?
}
};
base* base::maker() {
return new derived<double>();
}
int main() {
base* p = base::maker(); //p is derivedA<double>
p->func(); //p is now derivedA<int>
delete p; //is the compiler allowed to call ~derived<double>()?
}
这是我的代码的简短、独立、正确(可编译)的示例(基本上是any_iterator
为了我自己的成长而重新发明)。
问题归结为:当共享基础上没有任何其他成员时,使用从同一基础虚拟派生的不同类型进行销毁this
和重建是否是未定义的行为?具体来说,是否允许this
编译器调用静态类型的跟踪,或者这在技术上是不符合标准的?
[编辑] 一些人指出,如果derivedA
在堆栈上创建,编译器可能会调用不正确的析构函数。(1) 我在标准中找不到任何允许编译器这样做的东西。(2) 这与我的问题的意图不同,所以我更改了代码以显示derived
不能放在堆栈上。 base
虽然仍然可以在堆栈上。