Exercise 19.1 1 2 3 4 5 6 7 8 9 void *operator new(size_t size) { if(void *mem = malloc(size)) return mem; else throw bad_alloc(); } void operator delete(void *mem) noexcept {free(mem);} Exercise 19.2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // See StrVec.h and StrVec.cpp. void *operator new(size_t size) { cout << "operator new" << endl; if(void *mem = malloc(size)) return mem; else throw bad_alloc(); } void operator delete(void *mem) noexcept { cout << "operator delete" << endl; free(mem); } int main() { StrVec({"hello", "world"}); } StrVec.
Cpp-Primer-5th-Exercises-Chapter-18
Exercise 18.1 1 2 3 4 5 6 7 8 9 10 11 // range_error r("error"); // throw r; // type of exception object: range_error // exception *p = &r; // throw *p; // type of exception object: exception // the static, compile-time type of that expression determines the type of the exception object. // 'throw *p' replaced by throw p; // pointer points to a local object; // the matched catch expression may use this pointer to access a destructed object, which would casue an error, program terminates.
Cpp-Primer-5th-Exercises-Chapter-17
Exercise 17.1 1 2 3 4 5 int main() { tuple<int, int, int> ti(10, 20, 30); } Exercise 17.2 1 2 3 4 5 int main() { tuple<string, vector<string>, pair<string, int>> ti("hello", {"hello", "world"}, {"answer", 42}); } Exercise 17.3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // See TextQuery.
Cpp-Primer-5th-Exercises-Chapter-16
Exercise 16.1 1 2 3 // instantiate // generate a spedified version of function or class based on template and passed in template arguments. Exercise 16.2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 template <typename T> int compare(const T &v1, const T &v2) { if(v1 < v2) return -1; if(v2 < v1) return 1; return 0; } int main() { compare(1, 2); // compare(Sales_data(), Sales_data()); // compiler error: // .
Cpp-Primer-5th-Exercises-Chapter-15
Exercise 15.1 1 2 3 // What is a virtual member? // For some member functions, base class demands its derived class defines its own version, then base class defines them as virtual functions. Exercise 15.2 1 2 3 // members marked as protected could be visted by derived class, while still could not be visited by other user code; // members marked as private could not be visited by derived class and other user code.