How to return a GDI::Bitmap from a function

馋奶兔 提交于 2019-12-12 01:45:34

问题


How can I return a bitmap from a function? This code doesn't work: Compiler error

 Gdiplus::Bitmap create()
 {
       Gdiplus::Bitmap bitmap(10,10,PixelFormat32bppRGB);

       // fill image
       return bitmap;
 }

I don't want to return a pointer as then it generate a chance for memory leak. (or if there is way to avoid this chance of memory leak)


回答1:


When you return an object from a function, the compiler needs to generate code to either copy or (in C++11) move that object.

Gdiplus::Bitmap does not have an accessible copy constructor (and predates C++11, so no moving either) so you're not allowed to do this. Depending on how you're using it, you might consider using something like an std::unique_ptr or possibly an std::shared_ptr instead.

Alternatively, you might want to create the Bitmap in the parent, and simply pass a pointer or reference to it to have your function fill it in as needed.




回答2:


If you were wanting code. This is how you would pass the pointer back.

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

    // fill image
    return bitmap;
}

Would this not work?

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

Where the context would be something like

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

I'm not familiar with Gdiplus, so if there is no default constructor then that wouldn't work.



来源:https://stackoverflow.com/questions/19570133/how-to-return-a-gdibitmap-from-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!