我正在尝试链接一些函数,但在调用第一个函数后,调用析构函数;然后在范围的末尾再次调用析构函数。
int i=0;
class Winbitmap{
public:
int index=i++;
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::Bitmap* bitmap;
Winbitmap();
~Winbitmap();
Winbitmap& getCapture(int,int,int,int);
};
Winbitmap::Winbitmap(){ Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); }
Winbitmap::~Winbitmap(){
//{delete bitmap;}
std::wcout << L"destructed:" << index << std::endl;
Gdiplus::GdiplusShutdown(gdiplusToken);
}
Winbitmap& Winbitmap::getCapture(int x=0, int y=0, int w=0, int h=0) {
bitmap = new Gdiplus::Bitmap(captureWindow(GetDC(GetDesktopWindow()),x,y,w,h),NULL);
std::wcout << L"captured:" << index << std::endl;
return *this;
}
我打算如何使用它:
Winbitmap bitmap1 = Winbitmap().getCapture();
std::wcout<<L"confirmed1\n";
Winbitmap bitmap2 = Winbitmap().getCapture();
std::wcout << L"confirmed2\n";
//If I try to use any of the bitmaps later, the program hangs
Output:
captured:0
destructed:0
confirmed1
captured:1
destructed:1
confirmed2
destructed:1
destructed:0
如何在不调用析构函数的情况下正确返回对象的引用?
答案 0 :(得分:1)
该行:
Winbitmap bitmap1 = Winbitmap().getCapture();
创建临时对象,在临时对象上调用getCapture()
,调用复制构造函数构造bitmap1
,然后销毁临时对象。
您可以使用:
Winbitmap const& bitmap1 = Winbitmap().getCapture();
击> <击>然而,击>
我建议使用:
Winbitmap bitmap1;
bitmap1.getCapture();
阅读和理解更清楚。
答案 1 :(得分:0)
定义移动构造函数应该可以解决您的问题,前提是您可以使用C ++ 11(我很确定VS2013支持这一点):
WinBitmap::WinBitmap(WinBitmap&& bmp) : index(bmp.index), gdiplusToken(bmp.gdiplusToken), bitmap(bmp.bitmap) {
bmp.bitmap = NULL; // Because the new WinBitmap has now acquired ownership of the pointer.
}
然后你的析构函数会在bitmap
之前确保delete
不为空。