class room{
private :
int* array;
int xlength,ylength;
public :
room(int* data, int xL, int yL);
int GetXLength();
int GetYLength();
int* GetArray();
void ChangeRoom(int* data, int xL, int yL);
void InsertIntoArray(int* array2, int dim2x, int x, int y);
room* operator=(room* copy);
intoperator<(room* other);
intoperator==(room* other);
~room();
};
The problem is, when I use the list<room> type, the program will sometimes get a Segmentation fault. The exact error I get from the debugger is
After some research, I thought that the problem was the "int* array", which is dynamically allocated in room::room, and then destroyed with "delete [] array;" in room::room()~.
You're using pointers in so many places, I can't tell where the problem might come from. And the debugger output mentions std::list but I don't see it used in your code.
Just a heads up: In room::room(), if int *data is a dynamically allocated array, why not make int* data a reference to a pointer? It's not essential, but the method makes more sense with it.
That is the point. The compiler provide a trivial copy constructor, that it will copy every member.
So you end with a shallow copy, that causes a double delete.
@Framework: ¿? it is not modifying 'data' ¿why passing it by reference?
Also, I changed my methods by replacing "int* array" with "int array[]". But passing an array means giving a pointer to its first element, right ? So does it make a difference ?
Not quite right, a copy constructor takes a reference. Remember that this object will be constructed from the object passed in, there has been no initialization yet, and as such delete [] array; would likely cause a run time error.
You simply need to copy the members of the other object,
1 2 3 4 5 6 7
room(const room& copy)
: array(newint[copy.xlength * copy.ylength]),
xlength(copy.xlength), ylength(copy.ylength)
{
for (size_t i = 0; i < xlength * ylength; ++i)
array[i] = copy.array[i];
}
Ah, right. I already have a function which allows to change all the private variables (which is ChangeRoom), and I forgot to erase it after copying the code. I also changed my function so that the argument's type matches yours.
Still, I get the same error.
EDIT : I think I found what was causing the problem. I was creating a room inside a function as a local variable, then adding this room to a list<room> which was given to the function as a pointer.
Rewriting the function so that it returns the room and then adding this room to the list and deleting it after caused no problem.
But I don't understand why the problem was solved. Adding an element to a list creates a copy of this element, doesn't it ?