作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
考虑以下代码。是否保证Derived<int>::foo()
会被实例化吗? foo()
是虚函数,由基类的非虚函数调用。
#include <iostream>
class Base
{
public:
void bar() { foo(); }
private:
virtual void foo() = 0;
};
template <typename T> class Derived: public Base
{
public:
Derived(T t_) : t(t_) {}
private:
void foo() override { std::cout << t; }
T t;
};
Derived<int> make_obj()
{
return Derived<int>(7);
}
最佳答案
标准部分 14.7.1/11 说
It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated.
但是,对于典型的 vtable 实现,实例化类的任何构造函数都需要该类存在的 vtable,它必须包含指向特化虚函数定义的指针。所以在实践中,虚函数可能会被实例化。
关于c++ - 模板类的虚函数是隐式实例化的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41174161/
我是一名优秀的程序员,十分优秀!