尝试 clang++ 和 g++,两者的结果相同。
fatal error: recursive template instantiation exceeded maximum depth
template<class T>
struct Bar {
~Bar() {
if (ptr) { delete ptr; }
}
Bar<Bar<T>> * ptr{nullptr};
};
int main() { Bar<void> obj; }
但是 ctor 版本编译没有错误:
template<class T>
struct Bar {
Bar() {
if (ptr) { delete ptr; }
}
Bar<Bar<T>> * ptr{nullptr};
};
int main() { Bar<void> obj; }
dtor 版本有什么问题?
dtor 版本有什么问题?
想想像这样的声明Bar<void> obj;
意味着什么。
该对象需要在main
返回时调用其析构函数。所以析构函数~Bar<void>
将被实例化。
实例化的析构函数包含什么?一个delete
表情。您可能会认为它处于无效检查之下,因此永远不会被执行,但这并不重要。C++ 代码是静态解析的,即使编译器可以消除死代码,也必须是正确的。
该delete
表达式将需要调用 的析构函数Bar<Bar<void>>
,因此它必须被实例化......冲洗并重复。
另一方面,在构造函数版本中,您有一个简单的析构函数。它什么都不做,当然也不需要实例化任何其他类型。因此,当构造函数必须实例化它时,它编译得很好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句