[英]Destructor called after return *this
我正在嘗試鏈接一些函數,但是在調用第一個函數之后,就立即調用析構函數。 然后在作用域的末尾再次調用析構函數。
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
如何在不調用析構函數的情況下正確返回對對象的引用?
該行:
Winbitmap bitmap1 = Winbitmap().getCapture();
創建一個臨時對象, getCapture()
臨時對象調用getCapture()
,調用副本構造函數以構造bitmap1
,然后銷毀該臨時對象。
您可以使用:
Winbitmap const& bitmap1 = Winbitmap().getCapture();
然而,
我建議使用:
Winbitmap bitmap1;
bitmap1.getCapture();
這更容易閱讀和理解。
定義move構造函數應該可以解決您的問題,前提是您可以使用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
之前不為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.