我試圖鏈接一些函數,但在調用第一個函數之後,析構函數被調用;然後在範圍的末尾再次調用析構函數。析構函數在返回*之後調用
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
我怎樣才能回到正確的對象的引用,而不調用析構函數?
默認的拷貝構造函數被用來將'getCapture()'返回的臨時拷貝拷貝到'bitmap1'中。你忘了遵守[三項規則](https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming))。 –
我沒有看到「位圖」是一個指針的原因。連續調用兩次getCapture會泄漏內存。 – chris
位圖是不可複製的,所以我必須將它存儲在指針中。 – shuji