如何从函数返回 GDI::位图

How to return a GDI::Bitmap from a function

本文关键字:GDI 位图 返回 函数      更新时间:2023-10-16

如何从函数返回位图?此代码不起作用:编译器错误

 Gdiplus::Bitmap create()
 {
       Gdiplus::Bitmap bitmap(10,10,PixelFormat32bppRGB);
       // fill image
       return bitmap;
 }

我不想返回指针,因为它会产生内存泄漏的机会。(或者如果有办法避免这种内存泄漏的机会)

从函数返回对象时,编译器需要生成代码以复制或(在 C++11 中)移动该对象。

Gdiplus::Bitmap没有可访问的复制构造函数(并且早于 C++11,因此也不允许移动),因此不允许这样做。根据您使用的方式,您可以考虑改用std::unique_ptrstd::shared_ptr之类的东西。

或者,您可能希望在父级中创建Bitmap,只需传递指向它的指针或引用,即可让函数根据需要填充它。

如果你想要代码。 这就是将指针传回的方式。

Gdiplus::Bitmap* create()
{
    Gdiplus::Bitmap* bitmap = new Gdiplus::Bitmap(10,10,PixelFormat32bppRGB);
    // fill image
    return bitmap;
}

这行不通吗?

void create(Gdiplus::Bitmap& bitmap)
{
    bitmap = *(new Gdiplus::Bitmap(10,10,PixelFormat32bppRGB));
}

上下文类似于

int main()
{
    Gdiplus::Bitmap bitmap; //ONLY WORKS IF IT HAS DEFAULT CONSTRUCTOR
    create(bitmap);
}

我不熟悉 Gdiplus,所以如果没有默认构造函数,那么这将不起作用。