KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I found some code using std::shared_ptr<void> to perform arbitrary cleanup at shutdown. At first I thought this code could not possibly work, but then I tried the following: #include <memory> #include <iostream> #include <vector> class test { public: test() { std::cout << "Test created" << std::endl; } ~test() { std::cout << "Test destroyed" << std::endl; } }; int main() { std::cout << "At begin of main.\ncreating std::vector<std::shared_ptr<void>>" << std::endl; std::vector<std::shared_ptr<void>> v; { std::cout << "Creating test" << std::endl; v.push_back( std::shared_ptr<test>( new test() ) ); std::cout << "Leaving scope" << std::endl; } std::cout << "Leaving main" << std::endl; return 0; } This program gives the following output: At begin of main. creating std::vector<std::shared_ptr<void>> Creating test Test created Leaving scope Leaving main Test destroyed I have some ideas on why this might work, that have to do with the internals of std::shared_ptr as implemented for G++. Since these objects wrap the internal pointer together with the counter, the cast from std::shared_ptr<test> to std::shared_ptr<void> is probably not hindering the call of the destructor. Is this assumption correct? And, of course, the much more important question: Is this guaranteed to work by the standard, or might further changes to the internals of std::shared_ptr , and other implementations, actually break this code?
Tags (comma-separated)
Save Edits
Cancel