I am not sure to have fully understand when to use a smart pointers over raw pointers.
I have the following code structure.
First of all, Snake_cell
defined as follow
struct Snake_cell
{
Snake_cell(const unsigned int origin_x, const unsigned int origin_y)
unsigned int origin_x_;
unsigned int origin_y_;
};
Then, I have a Snake
which contains a vector
of Snake_cell
class Snake
{
public:
Snake(const unsigned int first_cell_x, const unsigned int first_cell_y);
private:
std::vector<std::shared_ptr<Snake_cell>> cells_;
};
Snake::Snake(const unsigned int first_cell_x, const unsigned int first_cell_y)
{
// Create three successives cells
cells_.emplace_back(std::make_shared<Snake_cell>(first_cell_x, first_cell_y));
cells_.emplace_back(std::make_shared<Snake_cell>(first_cell_x + CELL_SIZE, first_cell_y));
cells_.emplace_back(std::make_shared<Snake_cell>(first_cell_x + 2 * CELL_SIZE, first_cell_y));
}
Finally, I have a main.cpp
file following this format:
std::unique_ptr<Snake> snake(std::make_unique<Snake>(500-CELL_SIZE, 500-CELL_SIZE));
void func1(...)
{
}
void func2(...)
{
}
void func2(...)
{
}
/** Main **/
int main(int argc, char* argv[])
{
return 0;
}
Each of these functions either and some of them are rendering functions so they would be called a lot of time.
- access
Snake
attributes - modify
Snake
attributes
Hence, it made sense for me, in order to avoid unnecessary copy of Snake_cell
or Snake
objects to :
- Define a
vector
ofsmart pointers
toSnake_cell
withinSnake
- Create a
smart pointer
toSnake
withinmain.cpp
Yet, I think I'm not doing it right and could use raw pointers.
Are my assumptions correct to use
pointers
here? I know we are not dealing with a huge amount of data butfuncX
will be called a lot of time so it might become expensiveIf yes, am I right to use
smart pointers
here? I've read that there should be preferred over raw pointers every time I'm considering using pointers.If yes, am I right to use
shared_ptr
here? In my code, I'm creating a newsmart_ptr
object based onsnake
object everytime I need to use it. I feel like it's not the right way to use it.
For instance, here is one function I'm using.
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS);
for(unsigned int i = 0; i < snake->size(); ++i)
{
std::shared_ptr<Snake_cell> cell(snake->getCell(i));
glVertex2i(cell->origin_x_, cell->origin_y_);
glVertex2i(cell->origin_x_ + CELL_SIZE, cell->origin_y_);
glVertex2i(cell->origin_x_ + CELL_SIZE, cell->origin_y_ + CELL_SIZE);
glVertex2i(cell->origin_x_, cell->origin_y_ + CELL_SIZE);
}
glEnd();
glutSwapBuffers();
}
Thanks for your help,