我在与调整指针的数组,这主要与AddGraphicElement()函数的最后几行的问题。
我有一个VectorGraphic以下类定义:
unsigned int numGraphicElements;
GraphicElement* pElements;
public:
VectorGraphic();
~VectorGraphic()
{
if (pElements)
delete[]pElements;
}
void AddGraphicElement();
void DeleteGraphicElement();
void ReportVectorGraphic();
下面的类定义为GraphicElement的:
static const int SIZE = 256;
public:
unsigned int numLines;
Line* pLines;
char name[SIZE];
GraphicElement()
{
numLines = 0;
pLines = nullptr;
}
~GraphicElement()
{
if (pLines)
delete []pLines;
}
而下面的函数AddGraphicElement()在VectorGraphic class:
unsigned int numLines;
char name[256];
cout << "Adding a Graphic Element" << endl;
//Name input
cout << "Please enter the name of the new GraphicElement(<256 characters): ";
//Flush cin so it doesnt skip getline
cin.ignore();
cin.getline(name,sizeof(name));
//Line input
cout << "How many lines are there in the new GraphicElement? ";
cin >> numLines;
//Allocate memory for line(s)
Line* pLines = new Line[numLines];
for(int i=0;i<numLines;i++)
{
//Start point input
cout << "Please enter the x coord of the start point of line index " << i << ": ";
cin >> pLines[i].start.x;
cout << "Please enter the y coord of the start point of line index " << i << ": ";
cin >> pLines[i].start.y;
//End point input
cout << "Please enter the x coord of the end point of line index " << i << ": ";
cin >> pLines[i].end.x;
cout << "Please enter the y coord of the end point of line index " << i << ": ";
cin >> pLines[i].end.y;
}
//Allocate new size for GraphicElement*
GraphicElement* newElements = new GraphicElement[numGraphicElements+1];
//Copy old elements to new pointer
for(int i=0;i<numGraphicElements;i++)
{
newElements[i] = pElements[i];
newElements[i].pLines = pElements[i].pLines;
}
//Assign new element to last index
strcpy(newElements[numGraphicElements].name, name);
newElements[numGraphicElements].numLines = numLines;
newElements[numGraphicElements].pLines = pLines;
//Re-assign the pointer and increment number of elements
delete[] pElements;
pElements = newElements;
numGraphicElements++;
一直到最后3行似乎工作正常。如果我打印newElements的内容(删除和重新分配之前),我的所有数据都在那里。但是,如果我在删除和重新分配后打印它,我的数据就会丢失(取而代之的是垃圾值-17891602)。
我不认为我使用delete []正确,因为删除此行让我的工作方案,尽管有内存泄漏:
delete[] pElements;
我想我要问的是如何正确地做我在我的程序中使用delete []?
谢谢!
编辑:解决了,新代码,实现LOOP低于
strcpy(newElements[i].name, pElements[i].name);
newElements[i].numLines = pElements[i].numLines;
Line* newLines = new Line[newElements[i].numLines];
newLines->start.x = pElements[i].pLines->start.x;
newLines->start.y = pElements[i].pLines->start.y;
newLines->end.x = pElements[i].pLines->end.x;
newLines->end.y = pElements[i].pLines->end.y;
newElements[i].pLines = newLines;
你想要做的是分离担忧。你的班级不应该管理动态数组,它应该使用一些为你管理的东西。这是'std :: vector'。 – GManNickG
什么是[三条规则](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-reeree)?阅读链接并找出 – user4581301