PDA

View Full Version : problem with vector



mickey
14th September 2006, 01:11
Hi, it happen a weird thing; the first two cout (inside for) print right values: eg -2 -2 1 1 and 1 1 4 4; the second cout print two times the second element: 1 1 4 4 and 1 1 4 4; Why this? thanks..


//list.count() is = 2 in my test case
vector <GLfloat*> ppp;
GLfloat* Pos = new GLfloat[4];
for (uint i=0; i < list.count(); ++i) {
node = list.item(i);
xrett = node.toElement();
QString stringPOS = xrett.attribute("pos");
QStringList values( QStringList::split( ' ', stringPOS ) );
for( uint y = 0; y < values.size(); y++ ) {
Pos[ y ] = values[ y ].toFloat();
cout << "Pos[y] " << Pos[y] << endl;
}
ppp.push_back(Pos);
cout << "PPPPPP " << ppp[i][0] << " " << ppp[i][1] << " " << ppp[i][2] << endl;
}
for (int i=0; i < list.count() ; ++i)
cout << "PPPPPP " << ppp[i][0] << " " << ppp[i][1] << " " << ppp[i][2] << endl;

jacek
14th September 2006, 01:34
std::vector::push_back() doesn't copy the array, since it doesn't even know that you pass an array to it.

It should be:
vector <GLfloat*> ppp;
for (uint i=0; i < list.count(); ++i) {
GLfloat* Pos = new GLfloat[4]; // <---
...
ppp.push_back(Pos);
...
}

mickey
14th September 2006, 03:21
std::vector::push_back() doesn't copy the array, since it doesn't even know that you pass an array to it.

It should be:
vector <GLfloat*> ppp;
for (uint i=0; i < list.count(); ++i) {
GLfloat* Pos = new GLfloat[4]; // <---
...
ppp.push_back(Pos);
...
}
I don't understand your explain; maybe in my code I put the same 'space of memory' into ppp??? (space of memory' ->last modified Pos value)

lschien
14th September 2006, 05:17
I don't understand your explain; maybe in my code I put the same 'space of memory' into ppp??? (space of memory' ->last modified Pos value)

push_back( _T src ) just copy object src with type _T by calling copy construct of _T,
in your code, _T = GLfloat* , this is an integer of 4 bytes (32 bit mechine), so it is
a primitive type, just an integer, copy constructor is just copy the value, then
in your first for loop, all "pos" points to the same memory block, so push_back( pos )
copy the same integer value ( the same pointer), hence all value in ppp point to the
same memory block.

however, allocate new block pos in for loop may cause memory leakage, you may
deallocate pos before ppp is destructed, since destructor of vector would call destructor
of GLfloar* , but this is integer, it doesn't free memory block

best regards Lung Sheng Chien

Department of mathematics,
Tsing Hua university, R.O.C