03 August 2022

C++ 核心指南目录

“Prefer concrete types over class hierarchies”

理由

具体类比层级类更基础简单:容易设计、容易实现、容易使用、容易推导分析、轻巧、快速。如果要使用类层级,最好有充足的理由。

例子

class Point1 {
    int x, y;
    // ... operations ...
    // ... no virtual functions ...
};

class Point2 {
    int x, y;
    // ... operations, some virtual ...
    virtual ~Point2();
};

void use()
{
    Point1 p11 {1, 2};   // make an object on the stack
    Point1 p12 {p11};    // a copy

    auto p21 = make_unique<Point2>(1, 2);   // make an object on the free store
    auto p22 = p21->clone();                // make a copy
    // ...
}

如果一个类位于类层级中,你需要通过对象指针或引用去操作它。这意味着更多的内存开销、更多的内存分配和内存释放、更多的运行时开销、非直接的访问。

注意

具体类可以在栈中分配。可以是别的类的成员。