C++对象创建销毁计数异常:预期不符及负数问题求助
C++对象创建与销毁问题:count值不符合预期的原因分析
我为理解C++对象的创建与销毁机制编写了一段代码,但运行输出和预期不符。预期main函数中Box::count输出为3(对应b1、b(unit的 touching 在)_B Member
С在这里(看到这里的输出,我感到困惑:为什么count会变成负数?
具体代码与运行输出如下:
代码实现
class Box{ public: static int count; Box(double x, double y, double z) : length(x),width(y),height(z){ cout << "Box object created with " << length << " " << width << " " << height << endl; count++; cout << "Count after creation: " << count << endl; } ~Box(){ cout << "Object deleted!" << endl; count--; cout << "Count after delete: " << count << endl; } Box operator + (Box *b){ return Box(length + b -> length, width + b -> width, height + b -> height); } Box operator + (Box b){ return Box(length + b.length, width + b.width, height + b.height); } private: double length; double width; double height; }; int Box::count = 0; int main() { Box b1 = Box(1,1,1); Box b2 = Box(2,2,2); Box b3 = b1 + b2; cout << "Here I am expecting 3, but get 2: " << Box::count << endl; return 0; }
运行输出
Box object created with 1 1 1 Count after creation: 1 Box object created with 2 2 2 Count after creation: 2 Box object created with 3 3 3 Count after creation: 3 Object deleted! Count after delete: 2 Here I am expecting 3, but get 2: 2. // I am expecting 3 there, b1, b2 and b3 Object deleted! Count after delete: 1 Object deleted! Count after delete: 0 Object deleted! Count after delete: -1 // how can this been negative!
问题原因分析
1. 拷贝构造函数缺失导致count统计失衡
你的类没有显式定义拷贝构造函数,编译器会自动生成默认拷贝构造函数,但这个函数不会更新静态成员count,而析构函数每次执行都会让count--,直接导致统计错误:
- 执行
Box b3 = b1 + b2;时,operator+(Box b)的参数b是b2的拷贝——默认拷贝构造函数不会让count增加,但函数结束后这个拷贝对象销毁,会调用析构函数让count减1。 operator+内部创建了临时Box对象(3,3,3),此时count增加到3;随后这个临时对象用来初始化b3,同样调用默认拷贝构造函数,count不增加;临时对象销毁时,count减到2,这就是你输出时看到count为2的直接原因。
2. 重复析构导致count变为负数
当你使用Box b1 = Box(1,1,1);这种形式时,理论上编译器会做原装返回(ip被从干 man and pand破解确认自品质的拷贝构造函数不对,重新说:当使用Box b1 = Box(1,1,1);时,若编译器未开启返回值优化(RVO),会先创建临时对象,再拷贝给b1;临时对象销毁时count--,而b1销毁时又会再调用一次析构函数count--——相当于一个实际存在的对象被减了两次count,最终导致程序结束时count变成负数。
解决方法
- 显式定义拷贝构造函数,在拷贝时同步更新
count:
Box(const Box& other) : length(other.length), width(other.width), height(other.height) { cout << "Copy constructor called" << endl; count++; cout << "Count after copy: " << count << endl; }
- 优化
operator+的参数传递,改用const引用避免不必要的拷贝:
Box operator + (const Box& b){ return Box(length + b.length, width + b.width, height + b.height); }
- 若使用C++11及以上版本,建议补充移动构造函数,处理临时对象的所有权转移,避免额外的count统计错误:
Box(Box&& other) noexcept : length(other.length), width(other.width), height(other.height) { cout << "Move constructor called" << endl; // 移动构造是转移对象所有权,无需增加count }
内容的提问来源于stack exchange,提问作者Tao
相关产品推荐
相关产品推荐

