Isn't it bad if we use unique pointer in this case | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Isn't it bad if we use unique pointer in this case

Hi I tried to create a scenario of Chain of responsibility pattern as below: https://www.sololearn.com/compiler-playground/cBV3c5sLaUWn Is shared_pointer usage proper? I know it takes more overhead compared to unique pointer but this is the only choice. Right? If we could have used unique pointer , then ptrLevel1->setNextApprover(ptrLevel2); will enforce us to move ptrLevel2. Now, ptrLevel2 is not valid and cannot set third level approver on this null pointer. Is this correct? https://code.sololearn.com/cBV3c5sLaUWn/?ref=app

2nd Oct 2023, 7:51 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 2
Certainly, in the Chain of Responsibility pattern, using shared_ptr is a suitable choice because it allows multiple handlers to share responsibility for processing requests without ownership issues, which is common in this pattern. Using unique_ptr would restrict you from sharing handlers, making it less appropriate for this scenario.
2nd Oct 2023, 8:35 AM
D1M3
D1M3 - avatar
+ 1
Thanks
2nd Oct 2023, 9:45 AM
Ketan Lalcheta
Ketan Lalcheta - avatar