If I do it in a very similar way, it doesn't crash:
There is one "small" difference:
(1) this[r].resize(columns);
vs.
(2) matrix[r].resize(COLS);
(1) this[r].resize(columns);
vs.
(2) matrix[r].resize(COLS);
To copy to clipboard, switch view to plain text mode
Line (1) does not call "operator []" on this pointer like (2). Its equivalent to
*(this+r).resize(columns);
*(this+r).resize(columns);
To copy to clipboard, switch view to plain text mode
Can you see the problem ? Its like you want to access an array of objects using index r, where this should point to the first element. Obviously this array does not exists, so your program crashes.
You can fix this by changing (1) to:
(*this)[r].resize(columns);
(*this)[r].resize(columns);
To copy to clipboard, switch view to plain text mode
IMHO you should not subclass a QVector, it does not have a virtual destructor. Better use composition instead.
----
edit:
I've made a simple example to show this pointer arithmetic "magic":
#include <QDebug>
class Test{
public:
Test(){
}
void check(){
qDebug() << "this is" << x << ", next is:" << this[1].x;
}
int x;
};
int main(){
Test x[5];
for( int i=0 ; i<5 ; ++i ){
x[i].x = i;
}
for( int i=0 ; i<4 ; ++i ){
x[i].check();
}
}
// outputs:
// this is 0 , next is: 1
// this is 1 , next is: 2
// this is 2 , next is: 3
// this is 3 , next is: 4
#include <QDebug>
class Test{
public:
Test(){
}
void check(){
qDebug() << "this is" << x << ", next is:" << this[1].x;
}
int x;
};
int main(){
Test x[5];
for( int i=0 ; i<5 ; ++i ){
x[i].x = i;
}
for( int i=0 ; i<4 ; ++i ){
x[i].check();
}
}
// outputs:
// this is 0 , next is: 1
// this is 1 , next is: 2
// this is 2 , next is: 3
// this is 3 , next is: 4
To copy to clipboard, switch view to plain text mode
We create an array of 5 objects, assigned unique, ordered values. In method "check" we can access next element in that array, using pointer arithmetic ( this[1] = *(this+1) = next object in array ).
Don't use it in "real" code, its just for fun
Bookmarks