Saturday, September 13, 2008

std::vector and pointers.

STL vector is nice class , which allows us to randomly access any location in the vector.

But if you use pointers to reference memory inside the vector , it can be dangerous depends upon the situation.

Consider this example, I have declared a std::vector object for storing some objects of "SomeClass".

std::vector<SomeClass> Objects;
// i am feeding the vector here... like Objects.push_back( .. )

 After feeding the vector i just took the address of first object in the vector.

like SomeClass* pThink = &Objects[0];

This is fine and has no problems at all. But the problems will come if you keep feeding the vector or removing elements .. Because std::vector will always reorganizing memory .It make sure that the memory allocated for objects will be continous.

So if we refer the pointer 'pThink' after push/ remove functions , it can cause expcetion similar to pointing incorrect memory location etc.

No comments: