I am working on a physics engine related project. In the C++ code below:
#include <iostream>
#include <vector>
struct Vector3
{
float x;
float y;
float z;
};
struct object
{
std::vector < std::vector < Vector3 > > set_vertices;
int ID;
int Type;
};
class World
{
public:
std::vector< object > objects;
private:
// other members
};
int main (void)
{
World world;
// How to fill in "objects" of "world"?
// Is this safe to do?
world.objects.resize(5);
// What about the way of allocating "set_vertices" below?
for(size_t i=0; i<world.objects.size(); i++)
{
world.objects[i].set_vertices.resize(12, std::vector < Vector3 >(3));
for(size_t j=0; j<world.objects[i].set_vertices.size(); j++)
{
for(size_t k=0; k<world.objects[i].set_vertices[j].size(); k++)
{
world.objects[i].set_vertices[j][k].x = 0.0f;
world.objects[i].set_vertices[j][k].y = 0.0f;
world.objects[i].set_vertices[j][k].z = 0.0f;
world.objects[i].ID = i;
world.objects[i].Type = 0;
}
}
}
return 0;
}
is the way I have allocated memory for objects of world safe? There would be any memory related issue? Is there any better way of initializing objects dynamically (i.e. not in constructor)? If so, how? thanks.
I’d imagine that using RAII and having the constructor and destructor of
objectto take care of the memory would be a better way of doing this.Adding in a new
objectinto world you can make use ofstd::vectorability to resize dynamically by just callingpush_back()instead of needing to create the loop that hasias the index. To avoid unnecessary resizes if you know how many elements you are adding in advance you can call.reserve(n)wherenis the number of elements you are adding.