Coming from C#/Java background and I'm trying to understand best practices for using C++ pointers and references. I'm sure this has been covered ad nauseum on this site, but I still don't fully understand it. I've read some of the C++ FAQ but I need to see it in context. Suppose I have two classes:
class Employee
{
Employee();
~Employee();
}
class Company
{
Company();
~Company();
AddEmployee(?? employee);
?? GetEmployee();
private:
std::list<Employee??> employees_;
}
Where AddEmployee
takes an employee object and adds it to the private list of employees. What should the type of the AddEmployee
employee parameter be?
AddEmployee(Employee *employee);
AddEmployee(Employee& employee);
What template type should the private std::list be?
Also assuming the company class can modify the employee is const
appropriate here? And if I use a reference parameter, can the Company class turn around and pass the employee object to another class?
UPDATE
I see a lot of people suggesting using value semantics but coming from C#/java this is challenging. Generally I'm doing dependency injection using interfaces and I'm not sure if you can even use value semantics in this case. Can you code to interfaces using value semantics?
In the code I'm working on now pretty much all objects are allocated on the heap and my member functions looks like void TakeSomeObject(SomeObject *someObject)
or MyClass(SomeService *service)
. The code works although as the code grows more complicated I am worried about memory leaks as well. Part of what I was wondering if I should change those method signatures to use references instead and what the implications of doing that are.
Also when I read about smart pointers I wanted to go through my code and change most pointers to shared_ptr but it's not clear to me if this is a good thing or not. And in that case would I just change all my methods to take shared_ptr as parameter?
UPDATE 2
It seems like the consensus is to use either AddEmployee(const Employee& employee)
or AddEmployee(Employee& employee)
for heap allocated Employees. I'm open to change in the face of strong evidence but I don't see myself writing the value semantics version right now: AddEmployee(Employee employee)
UPDATE 3
I tried writing a method like:
AddEmployee(const Employee& employee)
{
employees_.push_back(??employee);
}
However this doesn't seem to work trying to replace ?? with nothing, &, or * when the list as defined as std::list<Employee*> employees_
. Does this mean I have to take a pointer parameter rather than a reference parameter to do something like this?