gpt4 book ai didi

c++ - 如何转发声明自定义 unique_ptr

转载 作者:搜寻专家 更新时间:2023-10-31 00:31:42 25 4
gpt4 key购买 nike

我在实现如下结构时遇到问题。这个想法是我在一些头文件中定义了一个实用函数,它分配某种资源。为了减轻客户自己释放它的必要性,我想将它包装成一个智能指针。不幸的是,我必须以某种方式将删除器类型提供给客户端,并且无法正确地转发声明它。我当前的解决方案看起来像这样,导致多个定义错误,因为删除器是用每个附加的 utilities.h 重新定义的

我正在寻找哪个优雅的解决方案?

// utilities.h
namespace foo
{
auto del = []( MyResource* res) { Deallocate( res ); };
std::unique_ptr<MyResource, decltype(del)> getResource( );
}

// utilities.cpp
namespace foo
{
std::unique_ptr<MyResource, decltype(foo::del)> getResource( )
{
return std::unique_ptr<MyResource, decltype(foo::del)>( Allocate( ), del );
}
}

最佳答案

使用普通类而不是 lambda:

标题:

namespace foo {

struct Deleter {
void operator() (MyResource *res) const { Deallocate(res); }
};

std::unique_ptr<MyResource, Deleter> getResource();
}

来源:

namespace foo
{
std::unique_ptr<MyResource, decltype(foo::del)> getResource( )
{
return std::unique_ptr<MyResource, Deleter>( Allocate( ) );
}
}

这还有一个额外的好处,就是在创建指针时不必指定删除器——默认构造的 Deleter 就可以了。

关于c++ - 如何转发声明自定义 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33523560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com