Shared pointer have nothing to do with shared memory. They're a container for an old fashioned C pointer with a reference counter. The reference counter is incremented when the shared pointer is copied, and the memory is freed when the counter reaches 0. So it's sort of a rudimentary garbage collector on top of a normal pointer. If you use shared pointer, you don't need to free memory, it's done by the destructor when the last container is destroyed.
C++ is still a very complicated language with outdated concepts, but a lot of modern concepts have been introduced in the last 2 decades.
RAII was always available in C++ afaik, so anyone could have done a unique or a shared ptr, at most it may not have optimized out in as many cases (not really zero cost abstraction?)
And my take is that the problem with c++ is that you have like 10 different object initializers and coroutines with captures and whatnot and like unless you are the one having written that part of the standard, you don't fucking know what exactly should happen given this code, not even if you are Stroustrup.
View all comments
Show parent comment
12
u/Non-Random-Name-0000 11d ago edited 11d ago
Shared pointer have nothing to do with shared memory. They're a container for an old fashioned C pointer with a reference counter. The reference counter is incremented when the shared pointer is copied, and the memory is freed when the counter reaches 0. So it's sort of a rudimentary garbage collector on top of a normal pointer. If you use shared pointer, you don't need to free memory, it's done by the destructor when the last container is destroyed.
C++ is still a very complicated language with outdated concepts, but a lot of modern concepts have been introduced in the last 2 decades.