Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is shared_ptr implemented using control block and not a static map?

To me, it looks like an implementation of std::shared_ptr which stores a reference counter in a static std::unordered_map<void*, struct Counters> would be much more simpler and also allow us to avoid some dirty workarounds like std::enable_shared_from_this (because std::shared_ptr<T>{this} wouldn’t create new control block, only increment a counter for a pointer that already exists in a map).

So why does a committee decided to stick with a control block implementation?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

So why does a committee decided to stick with a control block implementation?

It doesn’t. The committee writes requirements that implementers must follow. They do not specify that std::shared_ptr be implemented in any particular way, so long as that way meets the requirements.

Having said that, your proposed static std::map<T*, size_t> runs foul of this general requirement:

A C++ standard library function shall not directly or indirectly
access objects ([intro.multithread]) accessible by threads other than
the current thread unless the objects are accessed directly or
indirectly via the function’s arguments, including this.

[res.on.data.races#2]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading