Is this way to implement weak pointer as member is correct or not? | Sololearn: Learn to code for FREE!


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.

1/23/2022 5:52:56 PM

Ketan Lalcheta

5 Answers

New Answer


*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! :)


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 ?


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 :)


Okay... thank you


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