句柄而不是指针的引用计数
Reference count for a handle instead of a pointer
c++ 11引入了像std::shared_ptr
这样的智能指针。该类存储一个指针和一个引用计数器。当引用计数器为零时,将调用回调(删除器)。我的问题是c++ 11是否有一种简单的方法来使用std::shared_ptr
的引用计数器而不使用指针。
我使用一个c风格的库,它给我一个整数作为句柄。我想创建一个类来包装句柄。我想避免与std::shared_ptr
的间接,而我想有某种类型的引用计数关闭句柄时,它不再需要了。如果您可以分别使用createHandle
和destroyHandle
创建和销毁句柄,我认为它可能看起来像这样:
class WrapperClass
{
public:
WrapperClass() :
mHandle(createHandle(), &destroyHandle)
{
}
private:
shared_data<int> mHandle;
}
或
class WrapperClass
{
public:
WrapperClass() :
mHandle(createHandle()),
mRefCount([this](){destroyHandle(mHandle);})
{
}
private:
int mHandle;
reference_counter mRefCount;
}
另一个问题是,我不确定是否有可能像const
这样的工作说明符。我的意思是,不使用强制转换就不可能删除const
-说明符。我想不出有什么办法。
通过一些预防措施,您可以尝试使用原始shared_ptr来完成此任务:
#include <iostream>
#include <memory>
int create_handle() {
std::cout << "allocn";
return 42;
}
void delete_handle(int handle)
{
std::cout << "delete " << handle << "n";
}
class Wrapper
{
public:
Wrapper():
_d(Wrapper::create_handle(), &Wrapper::delete_handle)
{}
int value()
{
return reinterpret_cast<uintptr_t>(_d.get());
}
private:
std::shared_ptr<void> _d;
static void* create_handle()
{
static_assert(sizeof(create_handle()) <= sizeof(void*), "can't fit");
static_assert(alignof(create_handle()) <= sizeof(void*), "can't align");
return reinterpret_cast<void*>(static_cast<uintptr_t>(::create_handle()));
}
static void delete_handle(void* handle)
{
return ::delete_handle(reinterpret_cast<unintptr_t>(handle));
}
};
int main()
{
Wrapper w;
std :: cout << w.value();
}
我相信你必须确保你的句柄可以表示为指针(匹配大小和对齐)。然后你可以使用reinterpret_cast
黑魔法。由于您基本上只是使用reinterpret_cast将int
转换为指针并返回,但从未使用解引用指针,因此应该是安全的
相关文章:
- C++取消引用指针.为什么会发生变化
- 深层复制具有自引用指针的类
- Visual c ++,使用字符串引用/指针调用 dll 函数
- std::unordered_map::提取引用/指针失效
- 为什么在引用指针时将 const 放在 & 符号的左侧有效,而在右侧则无效?
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 如何在 c++ 中使用带有数学运算的引用/指针?
- 了解通过引用传递取消引用指针时C++堆/堆栈分配
- 取消引用指针并立即为其分配变量,导致分段错误
- 如何获取指向类(而不是对象)的引用/指针
- 将类型参数传递给自引用指针
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 在析构函数内取消引用指针时出现分段错误
- 来自引用指针的内存泄漏
- 引用指针后面的值
- 无法取消引用指针
- 引用指针调用成员函数
- 未定义的引用指针的变量模板在clang中功能,而不是GCC
- 取消引用指针以创建数组的副本
- 有关启动引用指针的引用的问题