All
simple code to use either unique_ptr or shared_ptr as a scope guard. All information what to clear is captured in the deleter, so I though it is safe to use nullptr for constructor. Apparently, with VisualC++ 2017 (14.1) it is not working as expected for unique_ptr, but works for shared_ptr. Is it a Microsoft quirk, or really standard prevents calling deleter of unique_ptr when it was initialized with nullptr ? IN the code below, I've forced to construct unique_ptr with (void*)1, if I construct it with nullptr, clear won't be called. For shared_ptr, there is no difference, cleaner is always called.
#include <memory>
#include <iostream>
int main()
{
int ttt = 77;
auto cleaner = [&ttt](void*) {
std::cout << "cleaner: " << ttt << "\n"; // do something with capture here instead of print
};
std::unique_ptr<void, decltype(cleaner)> p((void*)1, cleaner);
std::shared_ptr<void> q(nullptr, [&ttt](void*) {
std::cout << "shared: " << ttt << "\n"; // do something with capture here instead of print
});
std::cout << "done\n";
return 0;
}
Aucun commentaire:
Enregistrer un commentaire