我正在开发一个缓存,我需要知道一个对象何时到期.当shared_ptr的引用计数器减少时,是否可以运行一个函数?
std::shared_ptr< MyClass > p1 = std::make_shared( MyClass() );
std::shared_ptr< MyClass > p2 = p1; // p1.use_count() = 2
p2.reset(); // [ run function ] p1.use_count() = 1
Run Code Online (Sandbox Code Playgroud)
每次引用计数减少时都不能调用一个函数,但是当它达到零时你可以调用一个函数.您可以通过将"自定义删除器"传递给shared_ptr构造函数来执行此操作(您不能使用该make_shared实用程序); deleter是一个可调用对象,负责传递和删除共享对象.
例:
#include <iostream>
#include <memory>
using namespace std;
void deleteInt(int* i)
{
std::cout << "Deleting " << *i << std::endl;
delete i;
}
int main() {
std::shared_ptr<int> ptr(new int(3), &deleteInt); // refcount now 1
auto ptr2 = ptr; // refcount now 2
ptr.reset(); // refcount now 1
ptr2.reset(); // refcount now 0, deleter called
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
432 次 |
| 最近记录: |