C++ 计算不同类别对象的数量
我想计算我的程序在其生命周期内创建的对象的数量。根据此处提供的解决方案: 我有以下代码:C++ 计算不同类别对象的数量,c++,pass-by-reference,pass-by-value,C++,Pass By Reference,Pass By Value,我想计算我的程序在其生命周期内创建的对象的数量。根据此处提供的解决方案: 我有以下代码: #include <iostream> using namespace::std; using std::cout; using std::endl; template <typename T> struct counter { counter() { objects_created++; objects_alive++;
#include <iostream>
using namespace::std;
using std::cout;
using std::endl;
template <typename T>
struct counter
{
counter()
{
objects_created++;
objects_alive++;
}
virtual ~counter()
{
--objects_alive;
}
static int objects_created;
static int objects_alive;
};
template <typename T> int counter<T>::objects_created(0);
template <typename T> int counter<T>::objects_alive(0);
class X : counter<X>
{
int a;
};
class Y : counter<Y>
{
int b;
};
void fooX(class X x) {
cout << "passing object" << endl;
}
void fooY(class Y& y) {
cout << "passing reference" << endl;
}
int main()
{
cout << "created: " << " X:" << counter<X>::objects_created << " Y:" << counter<Y>::objects_created << endl;
cout << "alive: " << " X:" << counter<X>::objects_alive << " Y:" << counter<Y>::objects_alive << endl;
X x;
Y y;
cout << "created: " << " X:" << counter<X>::objects_created << " Y:" << counter<Y>::objects_created << endl;
cout << "alive: " << " X:" << counter<X>::objects_alive << " Y:" << counter<Y>::objects_alive << endl;
fooX(x);
fooY(y);
cout << "created: " << " X:" << counter<X>::objects_created << " Y:" << counter<Y>::objects_created << endl;
cout << "alive: " << " X:" << counter<X>::objects_alive << " Y:" << counter<Y>::objects_alive << endl;
int ui;
cin >> ui;
}
为什么创建的
X
s的数量不是2?复制构造函数会自动添加到计数器
类中,并且自动创建的复制构造函数不会增加静态变量
编写一个复制构造函数,该构造函数可执行以下操作:
counter(counter const&)
{
objects_created++;
objects_alive++;
}
请注意,除非您打算通过指向
计数器
的指针或引用删除派生类的动态创建实例,否则析构函数可能不应该是虚拟的。目前,这只是过早的悲观,因为它不必要地增加了对象的大小。您忘记了基类中的复制构造函数:counter(T const&)
@RichardCritten我有一个错误的理解,如果用户不提供,编译器会自动提供。让我试试你的建议。编译器确实提供了一个,但它可能不会做你想要的。默认的复制构造函数是非常非常愚蠢的。复制数据成员是绝对最少的(这使得指针和其他需要特殊处理的资源非常有趣。有关更多信息,请参阅),仅此而已。它不会增加计数器,也不会传递go和collect$200。还要简化operator=
的LHS对象中的计数器发生的情况,不要忘记复制省略:我在上面的代码中添加了counter(t const&t){objects\u created++;objects\u alive++}
,然后重新运行,它仍然给出了与我在OP中指出的相同的结果。也就是说,X创建的对象数仍然显示为1而不是2。@Tryer:这是因为计数器(T const&T)
不是复制构造函数。它只是一个普通的构造函数,使用T
,比如计数器(int number)
或者计数器(std::string const&text)
。是的。我把它改成了你答案中的密码,它就行了。非常感谢。
counter(counter const&)
{
objects_created++;
objects_alive++;
}