- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
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 << "alloc\n";
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
黑魔法。因为您基本上只是将 int
转换为指针并使用重新解释转换回来,但从不取消引用指针,所以它应该是安全的
关于c++ - 句柄而不是指针的引用计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33089102/
我设置了 Helm 柄和 Helm 柄。我有tiller-deploy。昨天,我可以定期运行了。但今天我收到此错误消息 Error: could not find a ready tiller pod
我以前已将分er安装到特定的 namespace 中。 我设置了一个环境变量来设置'tiller'命名空间-但我不记得该环境变量的名称-而且似乎无法通过网络搜索找到它。 这是什么 key ? 最佳答案
当我在 View 模型中使用如下界面时 class MainViewModel @ViewModelInject constructor( private val trafficImagesR
我正在尝试找到如何在某个 fragment 相关场景中定义 Hilt 的解决方案。我有以下设置: Activity 父 fragment 1 子 fragment 1 子 fragment 2 ...
Hilt 指出如果没有@Provides 注解就不能提供这个接口(interface): interface PlannedListRepository { fun getAllLists()
我的问题非常简单明了:两个注释/示例之间有什么区别: 例子一 @Singleton class MySingletonClass() {} @Module @InstallIn(FragmentCom
我是一名优秀的程序员,十分优秀!