std :: shared_ptr has an alias constructor that allows the newly created shared_ptr to share state with an existing shared pointer, pointing to some other object.
I was thinking about abusing this constructor to put a pointer to some global object inside shared_ptr:
int global = 0; int main() { // because we point to global object we do not need to track its lifetime // so we use empty shared_ptr<void> as a provider of shared state std::shared_ptr<int> p(std::shared_ptr<void>(), &global); std::shared_ptr<int> pp = p; return *pp; }
My question is: Is this legal? The code successfully works with the main compilers.
Note that I am not asking if this is good. I understand that there is a canonical way to put pointers to global objects in shared_ptr using no-op deleter. It is also a little troubling if it is legal, because one could have enforced shared_ptr, weak pointers to which always expired:
std::shared_ptr<int> p(std::shared_ptr<void>(), &global); std::weak_ptr<int> w = p; if (p)
c ++ language-lawyer c ++ 11
Grigory Shurenkov
source share