也许我误解了c++中智能指针的某些方面,但是在执行以下代码后:
class cls
{
public:
class deleter
{
public:
const cls& obj;
deleter(const cls& c) : obj(c) {}
void operator()(int* num)
{
std::cout << "deleter was called" << std::endl;
if (num)
{
std::cout << "num in deleter: " << *num << std::endl;
if (*num == *obj.int_ptr)
{
std::cout << "equal " << *num << " = " << *obj.int_ptr << std::endl;
delete num;
}
else
std::cout << "not equal" << std::endl;
}
}
};
std::shared_ptr<int> int_ptr;
cls() : int_ptr(nullptr,deleter(*this)) {}
};
int main()
{
cls obj;
obj.int_ptr.reset(new int{15});
return 0;
}
输出:
deleter was called
0
我注意到shared_ptr中的reset()删除了自定义删除器,该删除器在其构造函数中传递给了它。相反,unique_ptr没有显示这种行为,这对我来说很奇怪。
那么这是怎么回事?
最佳答案
当我们分配nullptr
或在std::shared_ptr上调用reset时,它将在清理内存后清除指针和getdeleter。对unique_ptr完成的方式有所不同。
下面是库中的函数,该函数将减少shared_ptr的计数,如果reference_count为零,则继续进行销毁:
void _Decref() noexcept { // decrement use count
if (_MT_DECR(_Uses) == 0) {
_Destroy();
_Decwref();
}
}
因此,一旦重置并且引用_count为零,则shared_ptr自定义删除器将由于重置而被删除。
关于c++ - 重置std::shared_ptr是否会导致重置其删除程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59260192/