int main (void) { std::cout << "compare (0, 42) = " << compare (0, 42) << std::endl; double* p = new double; DebugDelete d; d(p); //使用时, 可以自动推倒模板 int* ip = new int; DebugDelete() (ip); std::unique_ptr<int, DebugDelete> pi (new int, DebugDelete()); std::unique_ptr<std::string, DebugDelete> ps (new std::string, DebugDelete()); int ia[] = {9, 8, 7, 6, 5}; std::vector<long> vi = {5, 4, 3, 2, 1, 0}; std::deque<std::string> w = {"lady", "girl", "woman", "now"}; Blob<int> a1(std::begin(ia), std::end(ia)); Blob<int> a2(vi.begin(), vi.end()); Blob<std::string> a3(w.begin(), w.end()); std::cout << "int ia[] = "; for (const auto i : ia) { std::cout << i << " "; } std::cout << std::endl; std::cout << "std::vector<long> vi = "; for (const auto i : vi) { std::cout << i << " "; } std::cout << std::endl; std::cout << "std::list<const char*> w = "; for (const auto i : w) { std::cout << i << " "; } std::cout << std::endl; return 0; }
TextQuery::TextQuery(std::ifstream& ifs) : input(new vector<string>, DebugDelete()) { LineNo lineNo{0}; for (string line; std::getline(ifs, line); ++lineNo) { input->push_back(line); std::istringstream line_stream(line); for (string text, word; line_stream >> text; word.clear()) { // avoid read a word followed by punctuation(such as: word, ) std::remove_copy_if(text.begin(), text.end(), std::back_inserter(word), ispunct); // use reference avoid count of shared_ptr add. auto& nos = result[word]; if (!nos) nos.reset(new std::set<LineNo>, DebugDelete()); nos->insert(lineNo); } } }
QueryResult TextQuery::query(const string& str) const { // use static just allocate once. static shared_ptr<std::set<LineNo>> nodate(new std::set<LineNo>, DebugDelete()); auto found = result.find(str); if (found == result.end()) return QueryResult(str, nodate, input); else return QueryResult(str, found->second, input); }
void operator delete( void* mem ) { DebugDelete( mem, false ); }
void operator delete[]( void* mem ) { DebugDelete( mem, true ); }