我很好奇继承对非多态 类的影响。具体来说,我正在编写两个智能指针类,都没有使用虚方法,而且都用于非常独特的目的。由于基本运算符重载和一些标准函数是相同的,而且它们只需要一个成员变量,所以我想我可以使用一个基类来重用代码。这是我的意思的简单模型:
基类:
template <class T>
class Pointer_Impl
{
public:
T & operator*() { return this->*m_pointer; }
// etc.
protected:
T *m_pointer;
//protected to prevent instantiation without using = delete
Pointer_Impl() {}
Pointer_Impl(T *) {}
//other constructors, assignment and move operators, destructor here
};
然后:
template <class T>
class PointerA : public Pointer_Impl<T>
{
public:
PointerA() { m_pointer = nullptr; }
PointerA(T * obj) { m_pointer = obj; }
// other constructors, assignment and move operators, destructor, and any other class-specific functions here
};
问题:从缺少任何虚拟方法的基类派生时,是否会在内存或性能方面产生任何开销?由于它是一个智能指针实现,因此精益求精是我所追求的。
我的直觉告诉我没有,不用担心,但我想从更聪明的头脑中确定。
最佳答案
性能影响
没有。如果没有 virtual
(虚拟继承或虚拟函数),您将不会因使用基类而招致任何运行时惩罚。名称解析完全在编译时使用静态类型执行。
内存影响
没有。在没有 virtual
的情况下,继承的类与直接具有相同字段作为成员的类之间没有有意义的区别。如果您有多个基类或 virtual
(继承或函数),这一切都会改变。
编译影响
编译耗时可能会有一些影响;编译器将不得不跟踪更多的名称和模板实例化。这有时是大型、大量使用模板的代码库的一个问题。
关于c++ - 非多态继承对性能/内存使用有影响吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37941985/