【发布时间】:2014-02-20 20:44:56
【问题描述】:
对于我的代码,expand 是将向量的容量加倍。它应该为动态分配的数组动态重新分配内存并更新容量的值,同时不会造成内存泄漏。
我想知道您将如何检查内存泄漏,因为我的测试未在 Visual Studio 中显示执行时间。
void IntVector::expand(){
cap = cap * 2;
int *data2;
data2 = data;
IntVector::~IntVector();
data = new int[cap];
data = data2;
delete data2;
}
header(我知道您不应该使用命名空间 std)。
#ifndef INTVECTOR_H
#define INTVECTOR_H
using namespace std;
class IntVector{
private:
unsigned sz;
unsigned cap;
int *data;
public:
IntVector();
IntVector(unsigned size);
IntVector(unsigned size, int value);
unsigned size() const;
unsigned capacity() const;
bool empty() const;
const int & at (unsigned index) const;
const int & front() const;
const int & back() const;
~IntVector();
void expand();
};
#endif
主文件
#include "IntVector.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
IntVector::IntVector(){
sz = 0;
cap = 0;
data = NULL;
}
IntVector::IntVector(unsigned size){
sz = size;
cap = size;
data = new int[sz];
*data = 0;
}
IntVector::IntVector(unsigned size, int value){
sz = size;
cap = size;
data = new int[sz];
for(int i = 0; i < sz; i++){
data[i] = value;
}
}
unsigned IntVector::size() const{
return sz;
}
unsigned IntVector::capacity() const{
return cap;
}
bool IntVector::empty() const{
if(sz > 0){
return false;
}
else{
return true;
}
}
const int &IntVector::at(unsigned index) const{
if(index > sz){
exit(1);
}
else{
return data[index];
}
}
const int &IntVector::front() const{
return data[0];
}
const int &IntVector::back() const{
return data[sz];
}
IntVector::~IntVector(){
delete data;
}
void IntVector::expand(){
cap = cap * 2;
int *data2;
data2 = data;
IntVector::~IntVector();
data = new int[cap];
data = data2;
delete data2;
}
编辑::
void IntVector::expand(){
cap = cap * 2;
int *data2 = data;
data = new int[cap];
delete[] data2;
delete data2;
}
【问题讨论】:
-
你为什么要
data = data2;?这将使data指向您随后销毁的旧数据。 -
您还需要使用
delete[]来释放数组。而且你需要实现一个复制构造函数/赋值运算符。 -
我打算存储新数组的本地地址,以免丢失旧数组。
-
查找所有
= new并替换为make_unique、make_shared或vector -
void IntVector::expand(){ cap = cap * 2; int *data2 = 数据;数据=新的int [cap];删除[]数据2;删除数据2;这会改善原来的错误吗? *编辑:在原始帖子中发布我的编辑。
标签: c++