了解 CRTP 示例中的复制构造函数
Understanding copy-constructor in a CRTP example
我正在尝试了解 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]。他们为什么要申报?
I didn't understand the copy contstructor. Why did they do incrementing in it?
通过调用复制构造函数构造的对象应该算作构造的对象。
您的示例可以运行,因为它不使用复制构造函数。
使用:
X x;
X xx(x);
看看区别。
否则会默认生成拷贝构造函数,但不会计算创建的对象,如
X x1;
X x2(x1);
是的,演示在没有它的情况下也能工作,但没有以正确的方式计算对象。
我正在尝试了解 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]。他们为什么要申报?
I didn't understand the copy contstructor. Why did they do incrementing in it?
通过调用复制构造函数构造的对象应该算作构造的对象。
您的示例可以运行,因为它不使用复制构造函数。
使用:
X x;
X xx(x);
看看区别。
否则会默认生成拷贝构造函数,但不会计算创建的对象,如
X x1;
X x2(x1);
是的,演示在没有它的情况下也能工作,但没有以正确的方式计算对象。