使用CRTP时确保安全

Ensure safety while using CRTP

本文关键字:安全 确保 CRTP 使用      更新时间:2023-10-16

考虑以下使用CRTP 的代码片段

#include <iostream>
struct Alone
{
    Alone() { std::cout << "Alone constructor called" << std::endl; }
    int me {10};
};
struct Dependant
{
    explicit Dependant(const Alone& alone)
        : ref_alone(alone)
    { std::cout << "Dependant called with alone's me = " << alone.me << std::endl; }
    const Alone& ref_alone;
    void print() { std::cout << ref_alone.me << std::endl; }
};
template <typename D>
struct Base
{
    Base() { std::cout << "Base constructor called" << std::endl; }
    D* getDerived() { return static_cast<D*>(this); }
    Dependant f { getDerived()->alone };
    void print() { f.print(); }
};
struct Derived : Base <Derived>
{
    Derived() { std::cout << "Derived constructor called "  << std::endl; }
    Alone alone {};
    void print() { Base::print(); };
};
int main()
{
    Derived d;
    d.print();
}

原始链接http://coliru.stacked-crooked.com/a/79f8ba2d9c38b965

我有一个基本问题首先

  • 使用继承时如何进行内存分配?我知道构造函数是从Base调用到Derived的,但当我进行时

    派生d;

    分配相当于sizeof(D)的内存,然后调用构造函数。我的理解正确吗?(这将解释打印未初始化的成员)

  • 考虑到上面的例子,当涉及到CRTP时,你会建议/推荐任何最佳实践吗?

分配相当于sizeof(D)的内存,然后将构造函数称为

否则它怎么可能工作呢?不能在内存中构造尚未分配的对象。内存分配总是先于对象构造。

考虑到上面的例子,当涉及到CRTP时,你会建议/推荐任何最佳实践吗?

CRTP的标准做法是:不要在构造函数/析构函数中调用CRTP。虚拟函数也是如此。虚拟是动态多态性,而CRTP是静态多态性。但它们都使用相同的基本机制:基类定义派生类必须实现的接口。

就像使用虚拟函数一样,试图在构造函数/析构函数中调用它并不能达到你的目的。唯一的区别是,使用虚拟函数,编译器实际上会阻止您获得未定义的行为。而使用CRTP,您只会出现破损。

请注意,这包括默认的成员初始值设定项,出于非聚合的目的,它们只是构造函数初始化列表的简写。