问题
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