環境:
Visual studio 2017
boost庫編譯選項: msvc141,multi,win64,debug,shared
demo工程設定: debug, win32
問題源:
《Beyond the C++ STL: an introduction to boost》書上Part I, Library 3, checked_delete章節
如果把 deleter.h, deleter.cpp, to_be_deleted.h三個檔案内容整合到一個檔案裡,
編譯後會提示 " warning C4150: 删除指向不完整“to_be_deleted”類型的指針;沒有調用析構函數"
運作後調用 deleter::do_it 時會間接調用到 ~to_be_deleted()。
調用 deleter::delete_it 時則不會間接調用到 ~to_be_deleted()。
最後調用完 ~to_be_deleted()程式結束時才報一個異常錯誤。
很奇怪的地方啊!看來是編譯器工作方式的不同導緻的吧。。。
// deleter.h
class to_be_deleted;
class deleter {
public:
void delete_it(to_be_deleted* p);
void do_it(to_be_deleted* p);
};
// deleter.cpp
//#include "deleter.h"
#include "boost/checked_delete.hpp"
void deleter::delete_it(to_be_deleted* p) {
delete p;
}
void deleter::do_it(to_be_deleted* p) {
boost::checked_delete(p); // typedef char type_must_be_complete[sizeof(T)]; 所有代碼放入一個檔案,這句居然能編譯通過??
}
// to_be_deleted.h
#include <iostream>
class to_be_deleted
{
public:
~to_be_deleted() {
std::cout <<
"I'd like to say important things here, please.";
}
};
// Test application
//#include "deleter.h"
//#include "to_be_deleted.h"
int main() {
to_be_deleted* p = new to_be_deleted;
deleter d;
d.delete_it(p);
d.do_it(p);
}