c++ - C++。类中指针数组的赋值运算符
问题描述
我的任务是stack
使用指针数组创建类。但是,当我将一个类型的变量分配stack
给它自己时,堆栈(或数组)的元素就变成了垃圾。所以这里是代码(字段是和array
):stack_size
stack_capacity
stack& operator= (const stack& old)
{
if (stack_size != old.stack_size) {//array and old.array could be the same
delete[] array;
}
stack_size = old.stack_size;
stack_capacity = old.stack_capacity;
array = new int[stack_capacity];
for (size_t i = 0; i < stack_size; ++i) {
array[i] = old.array[i];
}
return *this;
}
但是,当我跑步时
std::cout << "Peek: " << c.peek() << " Size: " << c.size() << std::endl;
std::cout << c << "\n\n";
输出(分配前)是:
Peek: 300 Size: 6
{ -88, 99, -100, 0, 200, 300 }
分配后 (stk = stk) 是:
Peek: -842150451 Size: 6
{ -842150451, -842150451, -842150451, -842150451, -842150451, -842150451 }
可能是什么问题呢?有什么我想念的吗?谢谢
解决方案
因为*this
和old
是同一个对象,所以和this->array
是一样的old.array
。
这意味着您正在将未初始化的数据复制到
array = new int[stack_capacity];
进入自身。
传统的快速解决方法是首先检查自我分配,
if (this == &old)
return *this;
更现代的解决方案是“复制和交换”成语,您可以在线阅读。
推荐阅读
- xcode - Xcode 10.0 模拟器错误“Mach 错误 -308 - (ipc/mig) 服务器死亡”
- php - Codeigniter 图像未上传
- ssl - 启用 ssl 的 Jboss 远程处理
- c# - 即使文本框有数据,也会出现数据验证消息
- java - NumberFormatException - 如何解决?
- javascript - 批处理文件中的 WScript 是什么?
- php - PHP表单操作(POST)不发送到其他页面
- python - Pandas: how to compare several cells with a list/tuple
- android - Android:使用共享 EGL 上下文时内存泄漏
- apache-nifi - Nifi Cluster 从 kafka 读取重复数据