Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference and benefits of these two lines of code?

I have two lines of code I want explained a bit please. As much as you can tell me. Mainly the benefits of each and what is happening behind the scenes with memory and such.

Here are two structs as an example:

struct Employee 
{
    std::string firstname, lastname;
    char middleInitial;
    Date hiringDate; // another struct, not important for example
    short department;
};

struct Manager
{
    Employee emp; // manager employee record
    list<Employee*>group; // people managed
};

Which is better to use out of these two in the above struct and why?

list<Employee*>group;
list<Employee>group;
like image 931
maffo Avatar asked Dec 22 '22 11:12

maffo


2 Answers

First of all, std::list is a doubly-linked list. So both those statements are creating a linked list of employees.

list<Employee*> group;

This creates a list of pointers to Employee objects. In this case there needs to be some other code to allocate each employee before you can add it to the list. Similarly, each employee must be deleted separately, std::list will not do this for you. If the list of employees is to be shared with some other entity this would make sense. It'd probably be better to place the employee in a smart pointer class to prevent memory leaks. Something like

typedef std::list<std::shared_ptr<Employee>> EmployeeList;
EmployeeList group;

This line

list<Employee>group;

creates a list of Employee objects by value. Here you can construct Employee objects on the stack, add them to the list and not have to worry about memory allocation. This makes sense if the employee list is not shared with anything else.

like image 92
Praetorian Avatar answered Dec 24 '22 00:12

Praetorian


One is a list of pointers and the other is a list of objects. If you've already allocated the objects, the first makes sense.

like image 36
Scott C Wilson Avatar answered Dec 24 '22 02:12

Scott C Wilson