[英]What is necessary cleanup for CInternetSession
CInternetSession::Close()
的MSDN文檔只說
應用程序完成使用
CInternetSession
對象后調用此成員函數。
對於CHttpConnection
通過返回的對象CInternetSession::GetHttpConnection()
和CHttpFile
通過返回的對象CHttpConnection::OpenRequest()
做這些對象必須手動關閉並刪除?
我在MSDN上找不到CHttpConnection::Close()
的文檔,而CHttpFile
從CInternetFile
繼承了它的Close()
方法; 其文檔同樣無益:
關閉
CInternetFile
並釋放其任何資源。(對不起,我不能有三個鏈接)
我的直覺假設是,因為CInternetSession::GetHttpConnection()
和CHttpConnection::OpenRequest()
返回指針,並且因為CHttpConnection
的MSDN說
您永遠不會直接創建
CHttpConnection
對象; 相反,調用CInternetSession::GetHttpConnection
,它創建CHttpConnection
對象並返回指向它的指針。(對不起,我不能有三個鏈接)
CInternetSession
內部存儲對它生成的CHttpConnection
的引用,並在CHttpConnection
CInternetSession::Close()
時清理該對象。 這篇MSDN文章支持這一點, 該文章未提及連接對象的任何清理和狀態
處理CInternetSession對象 - >自動清理打開的文件句柄和連接。
這是必要的:
CInternetSession session(...);
CHttpConnection * connection = session.GetHttpConnection(...);
CHttpFile * file = connection->OpenRequest(...);
... Do stuff ...
file->Close();
delete file;
connection->Close();
delete connection;
session.Close();
或者它足以做到:
CInternetSession session(...);
CHttpConnection * connection = session.GetHttpConnection(...);
CHttpFile * file = connection->OpenRequest(...);
... Do stuff ...
session.Close();
如果---來自圖書館的文檔---不清楚清理資源的責任在哪里,有哪些可能的方法來檢測資源泄漏? 我知道Valgrind可以用於內存泄漏,但是文件句柄和其他可能被綁定的資源呢?
簡短的回答是你不必調用Close()
,它由MFC析構函數完成。 理想情況下,析構函數應該進行所有必要的清理。
正如您所指出的,MFC類的記錄很少。 WinINet函數有更好的文檔:
例如,它必須使用InternetCloseHandle
關閉::InternetOpen
句柄。 我們可以看看MFC類的定義並比較:
C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\atlmfc\\src\\mfc\\inet.cpp
CInternetSession(){
::InternetOpen //WinINet
...
}
CInternetSession::Close(){
::InternetCloseHandle //WinINet
...
}
CInternetSession::~CInternetSession(){
Close();
}
所以我們不需要調用internetSession.Close()
因為它是由析構函數自動完成的。 打電話不會有害。 我猜如果CInternetSession
是在堆上聲明的,那么我們可能需要Close()
因為在調用析構函數之前可能需要一些時間。
在另一個例子中,我們也不必調用Close
,但它不會受到傷害。
CHttpFile * file = connection->OpenRequest(...);
file->Close();//I think this is okay but not necessary because we "delete file" in next line
delete file;//calls Close(); and other necessary cleanups
精簡版:
CInternetSession session(...);
CHttpConnection *connection = session.GetHttpConnection(...);
CHttpFile *file = connection->OpenRequest(...);
//... Do stuff ...
delete file;//don't skip
delete connection;//don't skip
//session.Close();//you can skip, this gets called when we exist the function
順便說一句,在CInternetSession obj
上放置斷點並踩到它,也應該帶你到MFC文件..\\VC\\atlmfc\\src\\mfc\\inet.cpp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.