0

Shared pointer implementation

template<class T> class sharedptr { T* res; int* counter; }; If above is my code sample class to implement own shared pointer, Am i missing anything else? res is holding actual resource to be managed and counter is related to control block. control block is needed on heap as each object will have same memory location to increment or decrement the counter value. What else I am missing? Is anything else as a member variable is needed? One of my friend faced this feedback in interview that something is missing to be taken care , but not sure what it is.

28th Aug 2024, 1:52 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 Respostas
+ 1
thread safe custom shared ptr is tricky. here is a link I found that uses atomic reference counter. https://github.com/yalekseev/shared_ptr/tree/master I copy-pasted the code in Sololearn's codebit, deleted the namespaces, added the test.cpp, did some personal preference changes and corrected some errors in the tests, and it seems to run ok. The asserts are passing. https://sololearn.com/compiler-playground/cp6oAMHtyGBF/?ref=app it doesn't implement weak pointer, though... that would be another bit of complication. But one should never expect these things to be simple...
30th Aug 2024, 3:27 PM
Bob_Li
Bob_Li - avatar
+ 1
Thanks. Will take a look
30th Aug 2024, 3:29 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
I got two information from other friend as below : 1. It should handle multithread. Hence int* should take care of multiple thread either by mutex or atomic<int> or atomic<int*> 2. Along with shared pointer strong counter, it should have weak pointer counter to check whether object block has expired or not through control block. More details of this second point as below: https://stackoverflow.com/questions/49585818/why-does-shared-ptr-needs-to-hold-reference-counting-for-weak-ptr
28th Aug 2024, 4:21 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
😂😂🤣
29th Aug 2024, 1:24 PM
Uui Jh
Uui Jh - avatar
0
There doesn't seem to be a multi threading test. How would you do that?
30th Aug 2024, 3:40 PM
Bob_Li
Bob_Li - avatar