I have noticed strange behavior (IMO) on MSVC 14 Comm. in Debug x86 solution. Code below throws Exception when vector::resize is not included. Note: after assigment some entities may be unassigned by passing nullptr.
vector<Entity*> m_entities;
(...)
// find empty slot
u_int id = m_entities.size();
for(u_int i=0; i<m_entities.size(); ++i)
{
if(m_entities[i] == nullptr)
{
id = i;
break;
}
}
// vector realloc
if(id == m_entities.capacity())
{
u_int newSize = m_entities.capacity() * 2;
m_entities.reserve(newSize);
//m_entities.resize(newSize);
}
// assign
entity->m_id = id;
m_entities[id] = entity;
It looks like operator[] checks size() instead of capacity() - am I right?
You can NOT access the reserved area of the vector
if it was not initialized. reserve
does not initialize anything it just reserve (as it was named) some memory to not reallocate
the vector
each time a new item is pushed back
Try to run this code:
#include <iostream>
#include <string>
#include <vector>
class my_class{
public:
my_class(){
x="I am an initialized item";
}
std::string x;
};
int main()
{
std::vector<my_class> v(2);
v.reserve(3);
std::cout << v[0].x <<std::endl<< v[1].x <<std::endl <<v[2].x;
}
You may got compiling error in the debug mode(depending on your compiler), it may pass and give undefined behaviour (NOT sure about undefined behaviour please someone edit this part). In best case, it would run with printing empty string for v[2]
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments