理解CRTP示例中的复制构造函数

Understanding copy-constructor in a CRTP example

本文关键字:复制 构造函数 CRTP 理解      更新时间:2023-10-16

我试图理解CRTP的一个简单用例。以下是来自wiki 的示例

template <typename T>
struct counter
{
    static int objects_created;
    static int objects_alive;
    counter()
    {
        ++objects_created;
        ++objects_alive;
    }
    counter(const counter&)
    {
        ++objects_created;
        ++objects_alive;
    }
protected:
    ~counter() // objects should never be removed through pointers of this type
    {
        --objects_alive;
    }
};
template <typename T> int counter<T>::objects_created( 0 );
template <typename T> int counter<T>::objects_alive( 0 );
class X : counter<X>
{
    // ...
};

我不懂复印件的结构。他们为什么在里面做递增?此外,我删除了它,这个例子也很好[DEMO]。他们为什么要申报?

我不懂复印件的结构。他们为什么在里面做递增?

通过调用复制构造函数构造的对象应算作构造的对象。

您的示例之所以有效,是因为它不使用复制构造函数。

用途:

X x;
X xx(x);

看看区别。

否则,复制构造函数将默认生成,但不会像那样计算创建的对象

X x1;
X x2(x1);

是的,demo在没有它的情况下工作,但不能以正确的方式计算对象。