在返回*this后调用析构函数

Destructor called after return *this

本文关键字:调用 析构函数 this 返回      更新时间:2023-10-16

我试图链接一些函数,但在调用第一个函数后,析构函数被调用;然后在作用域结束时再次调用析构函数。

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"confirmed1n"; 
Winbitmap bitmap2 = Winbitmap().getCapture();
std::wcout << L"confirmed2n";
//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(),调用复制构造函数来构造bitmap1,然后销毁临时对象。

可以使用:

Winbitmap const& bitmap1 = Winbitmap().getCapture();
然而,

我建议使用:

Winbitmap bitmap1;
bitmap1.getCapture();

定义移动构造函数应该可以解决您的问题,前提是您可以使用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.
}

那么你的析构函数将确保bitmapdelete之前不为空。