如何使用自定义删除器分配 unique_ptr

How to assign a unique_ptr with a custom deleter

我试图传递一个指向函数的指针,然后在结构中将 unique_ptr 设置为传入的指针。但是,我在函数的最后一行收到以下编译错误。

error C2280: 'std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>>::unique_ptr(const std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>> &)' : attempting to reference a deleted function

c:\program files (x86)\microsoft visual studio 12.0\vc\include\memory(1486) : see declaration of 'std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>>::unique_ptr'

This diagnostic occurred in the compiler generated function 'Skin::Skin(const Skin &)'

从错误来看,我认为这与我将 ALLEGRO_BITMAP 的删除模板添加到名称空间标准有关,但我不知道为什么或如何修复它。

using namespace std;

namespace std {
template<>
class default_delete < ALLEGRO_BITMAP > {
public:
    void operator()(ALLEGRO_BITMAP* ptr) {
        al_destroy_bitmap(ptr);
    }
};
}

typedef struct {
    unique_ptr<ALLEGRO_BITMAP> img;
} Skin;

typedef struct {
    Skin skins[MAX_ENTITY_COUNT];
} World;

unsigned int createBlock(World world, ALLEGRO_BITMAP* img) {
    unsigned int entity = newEntityIndex(world);
    world.skins[entity].img = make_unique<ALLEGRO_BITMAP>(img);
    return entity;
} // error on this line

感谢任何帮助。谢谢。

在您的 createBlock 函数中,您按值获取 World,这意味着它将被复制。但是,您不能复制 unique_ptr 所以这就是您的错误来源。这也意味着在函数中设置 unqiue_ptr 不会有任何效果。

相反,您应该参考 World:

unsigned int createBlock(World& world, ALLEGRO_BITMAP* img) {
    unsigned int entity = newEntityIndex(world);
    world.skins[entity].img = make_unique<ALLEGRO_BITMAP>(img);
    return entity;
}

请注意,对 newEntityIndex 的调用也是如此,make_unique 的参数将传递给 ALLEGRO_BITMAP 构造函数。

所以你可能想要的是:

world.skins[entity].img.reset(img);