Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cpp idioms

Rule of zero

If you can avoid defining default operations, do.

Rule of five

If you define or =delete any copy, move, or destructor function, define or =delete them all.

If not define move operations then they won’t generated. Move calls will fall back to copy operations. If you define any copy, copy assignment operator or destructor, define them all.(rule of three)

C++ 11 or later, you should be following the Rule of five.

class X {
public:
    virtual ~X() = default;            // destructor (virtual if X is meant to be a base class)
    X(const X&) = default;             // copy constructor
    X& operator=(const X&) = default;  // copy assignment
    X(X&&) = default;                  // move constructor
    X& operator=(X&&) = default;       // move assignment
};

CRTP

Curiously Recurring Template Pattern

CRTP 的范式基本上都是:父类是模板,再定义一个类类型继承它。 因为类模板不是类,只有实例化后的类模板才是实际的类类型, 所以我们需要实例化它,显式指明模板类型参数, 而这个类型参数就是我们定义的类型,也就是子类了。

template <class Dervied>
class Base {};

class X : public Base<X> {};

CRTP 可用于在父类暴露接口,而子类实现该接口,以此实现“编译期多态”,或称“静态多态”

template <class Dervied>
class Base {
public:
    // 公开的接口函数 供外部调用
    void addWater(){
        // 调用子类的实现函数。要求子类必须实现名为 impl() 的函数
        // 这个函数会被调用来执行具体的操作
        static_cast<Dervied*>(this)->impl();
    }
};

class X : public Base<X> {
public:
    // 子类实现了父类接口
    void impl() const{
        std::cout<< "X 设备加了 50 毫升水\n";
    }
};

C++23 的改动-显式对象形参

struct Base { void name(this auto&& self) { self.impl(); } };
struct D1 : Base { void impl() { std::puts("D1::impl()"); } };
struct D2 : Base { void impl() { std::puts("D2::impl()"); } };

不再需要使用 static_cast 进行转换,直接调用即可。

CRTP 的好处

  1. 静态多态

    CRTP 实现静态多态, 无需使用虚函数,静态绑定,无运行时开销。

  2. 类型安全

    CRTP 提供了类型安全的多态性。 通过模板参数传递具体的子类类型, 编译器能够确保类型匹配, 避免了传统向下转换可能引发的类型错误。

  3. 灵活的接口设计

    CRTP 允许父类定义公共接口, 并要求子类实现具体的操作。 这使得基类能够提供通用的接口, 而具体的实现细节留给派生类。 其实也就是说多态了。

RVO

Return value optimization

SFINAE

Substitution Failure Is Not An Error

C++ ADL(Argument-dependent lookup)

UAF

Use after free. use-after-free

https://en.cppreference.com/w/cpp/language/adl.html