![](/img/trans.png)
[英]How to move a unique_ptr without custom deleter to another unique_ptr with custom deleter?
[英]How to assign a unique_ptr with a custom deleter
我试图传递一个指向函数的指针,然后将该函数内部的结构中的unique_ptr
设置为传入的指针。但是,在函数的最后一行出现以下编译错误。
错误C2280:'std :: unique_ptr <ALLEGRO_BITMAP,std :: default_delete <ALLEGRO_BITMAP >> :: unique_ptr(const std :: unique_ptr <ALLEGRO_BITMAP,std :: default_delete <ALLEGRO_BITMAP >>&)':试图引用已删除的函数
c:\\ program files(x86)\\ Microsoft Visual Studio 12.0 \\ vc \\ include \\ memory(1486):请参见'std :: unique_ptr <ALLEGRO_BITMAP,std :: default_delete <ALLEGRO_BITMAP >> :: unique_ptr'的声明
此诊断发生在编译器生成的函数'Skin :: Skin(const Skin&)'中
从错误的角度来看,我认为这与将ALLEGRO_BITMAP
的删除模板添加到名称空间std有关,但是我不知道为什么或如何解决它。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.