在 return *this 之后调用的析构函数

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

如何在不调用析构函数的情况下return正确引用对象?

行:

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 之前不为 null。