+ 4

Is this way to implement weak pointer as member is correct or not?

Hi I have an employee class which is derived to manager class. Employee can be referred to a manager object suggesting direct reportees. I have tried managing this using smart pointers. Is this ok? Would appreciate your feedback on this. https://code.sololearn.com/c1L5BmNcR8xM

23rd Jan 2022, 5:52 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Respuestas
+ 6
*Puts on glasses* Line 37 is incorrect since your weak_ptr may have expired by then, resulting in a null reference exception. You need to check whether the `lock` was successful. Your `AddReportee` lets you add the same employee twice, but your `RemoveReportee` will only remove one occurrence. It's probably better if you do `remove_if` to filter the entire list. (And if you're filtering the whole list anyway you could also use this opportunity to remove all the expired weak pointers, for no extra cost!) Looks good otherwise! :)
23rd Jan 2022, 11:31 PM
Schindlabua
Schindlabua - avatar
+ 2
Thanks Schindlabua Updated code for both the points 1. Added expired check before calling display function 2. Add reportee updated to stop adding same reportee Thanks once again... Feel free to share thoughts on this... Also shared_ptr is good option here and vector of weak pointer is good option or not ?
24th Jan 2022, 5:06 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
I see... maybe an alternative could be to have only an Employee class, and an `isManager` function that returns true if the employee has any reportees? Otherwise I would leave it like you implemented it. Concerning weak pointers, I would probably just use strong pointers here since your `display` function creates a new shared_ptr anyway. But weak_ptr is fine too, I think it would depend on what this code would be used for in a "real life" scenario :)
24th Jan 2022, 12:38 PM
Schindlabua
Schindlabua - avatar
+ 2
Okay... thank you
24th Jan 2022, 1:54 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
And other concern is about addreportee method ... Whether it should be part of employee class or manager class... I feel that manager class is proper one as I implemented because every employee might not be manager But issue is that I can't have all pointer of employee class to achieve polymorphism because addreportee is not there now in employee class
24th Jan 2022, 5:50 AM
Ketan Lalcheta
Ketan Lalcheta - avatar