我正在尝试将unique_ptr
自定义删除器用于SDL_Surface
类型。这只是使用int
类型的示例,但希望您能理解。
#include <iostream>
#include <functional>
#include <memory>
typedef int SDL_Surface;
SDL_Surface * CreateSurface()
{
SDL_Surface * p = new SDL_Surface;
return p;
}
void FreeSurface(SDL_Surface *p)
{
delete p;
}
int main() {
std::unique_ptr<SDL_Surface, std::function< void (SDL_Surface *) > > uptr_1;
//how to assign a value to uptr_1 and the deleter?
return 0;
}
是否uptr_1
正确声明并初始化为nullptr
?如果是这样,如何分配指针和删除器功能?
我怎么封装呢:std::unique_ptr< SDL_Surface, std::function< void (SDL_Surface *) > >
用删除器不总是在SDL_Surface
我想要的每一个typedef上写那一行?
我才刚刚开始学习C ++ 11功能,这对我来说很难。
您可以unique_ptr
使用指针和删除器初始化,也可以在=
以后重新分配时正常使用:
std::unique_ptr<SDL_Surface, std::function<void (SDL_Surface *)>> uptr_1(CreateSurface(), &FreeSurface);
uptr_1 = std::unique_ptr<SDL_Surface, std::function<void (SDL_Surface *)>>(CreateSurface(), &FreeSurface);
有关详细信息,请参考合适的文档。
要缩短长类型,您确实可以使用类型别名(typedef
或using
):
typedef std::unique_ptr<SDL_Surface, void (*)(SDL_Surface*)> Surface_ptr;
//or
using Surface_ptr = std::unique_ptr<SDL_Surface, void (*)(SDL_Surface*)>;
注意,我实际上已经使用void (*)(SDL_Surface*)
了删除器类型。如果您知道将始终传递一个实际函数(或无状态lambda),则没有理由拖入std::function
,由于类型擦除会产生一些开销。
另外,您可以通过为删除程序创建默认可构造的仿函数来进一步缩短它:
struct FreeSurface_Functor
{
void operator() (SDL_Surface *s) const
{
FreeSurface(s);
}
};
这样,您可以创建指针的类型std::unique_ptr<SDL_Surface, FreeSurface_Functor>
(可能是别名),而不必提供删除程序。它是默认构造的:
std::unique_ptr<SDL_Surface, FreeSurface_Functor> uptr_1(CreateSurface());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句