Reputation: 3847
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.
Upvotes: 0
Views: 167
Reputation: 15924
I'd imagine that using RAII and having the constructor and destructor of object
to take care of the memory would be a better way of doing this.
Adding in a new object
into world you can make use of std::vector
ability to resize dynamically by just calling push_back()
instead of needing to create the loop that has i
as the index. To avoid unnecessary resizes if you know how many elements you are adding in advance you can call .reserve(n)
where n
is the number of elements you are adding.
Upvotes: 2
Reputation: 385098
It's safe.
You could save boilerplate by moving all that filling into a constructor, if appropriate.
You might also be able to find a more efficient approach than levels of nested vectors.
So, it's safe but could still be improved.
Upvotes: 1