在返回*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"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.
}
那么你的析构函数将确保bitmap
在delete
之前不为空。
相关文章:
- 什么时候调用析构函数
- C++-明确何时以及如何调用析构函数
- C++ 防止在映射中放置()时调用析构函数
- 调用析构函数以释放动态分配的内存
- C++:使用方法调用析构函数的顺序是什么?
- 向量推回调用析构函数时调用析构函数
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- C++,我应该调用析构函数吗?
- 如何获取有关在 Clang LibTooling 中调用析构函数的信息?
- 当我从 std::vector 中的新放置调用析构函数时会发生什么?
- 为什么这里不调用析构函数
- 在调用 std::bind 的产品后意外调用析构函数
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 如何在C++中调用析构函数
- 为什么为未删除的对象调用析构函数?
- 调用析构函数时出错
- C++ 在不释放内存的情况下调用析构函数
- 为什么在运算符删除中不调用析构函数?
- C++ 调用析构函数后动态模板队列"double free or corruption (out)"
- 在 postOrderDelete 上调用析构函数时引发的异常