使用unique_ptr或shared_ptr作为范围保护的简单代码.有关清除内容的所有信息都在删除器中捕获,因此我尽管将nullptr用于构造函数是安全的. 显然,使用Visual C 2017(14.1),它不能像unique_ptr那样工
显然,使用Visual C 2017(14.1),它不能像unique_ptr那样工作,但适用于shared_ptr.这是微软的怪癖,还是标准阻止在持有nullptr时调用unique_ptr的删除?
在下面的代码中,我被迫用(void *)1构造一个unique_ptr.如果我使用nullptr构造它,则不会调用cleaner.对于shared_ptr,没有区别,总是调用清理器.
#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;
}
unique_ptr的析构函数需要这样做:
23.11.1.2.2 unique_ptr destructor [unique.ptr.single.dtor]
2 Effects: If
get() == nullptrthere are no effects. Otherwiseget_deleter()(get()).
实际上shared_ptr的析构函数需要执行相同的操作:
23.11.2.2.2 shared_ptr destructor [util.smartptr.shared.dest]
— (1.1) If
*thisis empty or shares ownership with anothershared_ptrinstance (use_count() > 1), there are no side effects.— (1.2) Otherwise, if
*thisowns an object p and a deleter d, d(p) is called.
所以依靠智能指针在传递空指针时在范围出口执行任意操作是不可靠的.
