我們有幾個單元測試使用Win32 _CrtMemCheckpoint
/_CrtMemDifference
方法來檢測被測代碼中的內存泄漏。在x64機器上(Windows 7),其中一些測試報告了x86(32位)機器上未報告的內存泄漏。在這些x64計算機,編譯以下代碼要麼VS2008或VS2012和使用Boost 1.52.0,結果是「內存泄漏檢測!」:boost :: filesystem :: path導致內存差異
#include <boost/filesystem.hpp>
#include <crtdbg.h>
int main(int argc, char **argv)
{
_CrtMemState state1, state2, state3;
_CrtMemCheckpoint(&state1);
{
boost::filesystem::path remoteDirPath("c:/");
}
_CrtMemCheckpoint(&state2);
int res = _CrtMemDifference(&state3, &state1, &state2);
if (res != 0)
{
_CrtDumpMemoryLeaks();
std::cout << "Memory leak detected!";
}
}
這是實際的boost ::文件系統中的內存泄漏: :路徑?我想這是一些庫initalization左右,因爲
int main(int argc, char **argv)
{
{
boost::filesystem::path initDummy("c:/");
}
_CrtMemState state1, state2, state3;
_CrtMemCheckpoint(&state1);
{
boost::filesystem::path remoteDirPath("c:/");
}
_CrtMemCheckpoint(&state2);
int res = _CrtMemDifference(&state3, &state1, &state2);
if (res != 0)
{
_CrtDumpMemoryLeaks();
std::cout << "Memory leak detected!";
}
}
不會輸出「內存泄漏檢測!」。
我的問題是:如何避免單元測試出現這樣的問題?在開始測試之前初始化這樣一個變量是否是解決方案?在使用其他代碼時,我還需要做更多這樣的事情嗎?或者通常做這樣的測試是一個壞主意?
感謝您的想法!