Master exception handling, templates, and modern C++ smart pointers.
Write robust, generic, and memory-safe C++ code.
try {
// Code that might throw
throw runtime_error("Error!");
} catch (const exception& e) {
cout << "Caught: " << e.what();
}try - wrap risky codethrow - signal an errorcatch - handle the errordouble divide(double a, double b) {
if (b == 0) {
throw invalid_argument("Division by zero!");
}
return a / b;
}try { ... }
catch (const invalid_argument& e) { ... }
catch (const out_of_range& e) { ... }
catch (const exception& e) { ... } // catches allruntime_error - general runtime errorsinvalid_argument - bad function argumentsout_of_range - index out of boundslogic_error - logical errors in code10 / 2 = 5
Error: Division by zero!
Program continues normally...
throw runtime_error("message");catch (const exception& e) { e.what(); }Review feedback below
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}template <typename T> declares a type parameterT is a placeholder for any typeint maxInt = getMax(5, 10); // T = int
double maxDouble = getMax(3.14, 2.7); // T = double
char maxChar = getMax('a', 'z'); // T = chartemplate <typename T, typename U>
void printPair(T first, U second) {
cout << first << ", " << second << endl;
}template <typename T>
void mySwap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}Max of 5 and 10: 10
Max of 3.14 and 2.7: 3.14
Before swap: a=5, b=10
After swap: a=10, b=5
template <typename T>T& a, T& bReview feedback below
#include <memory>unique_ptr<int> ptr1 = make_unique<int>(42);
cout << *ptr1 << endl; // Dereference like regular pointer
// Memory freed automatically when ptr1 goes out of scopeshared_ptr<int> ptr2 = make_shared<int>(100);
shared_ptr<int> ptr3 = ptr2; // Both point to same object
cout << ptr2.use_count(); // Prints 2class Resource {
public:
Resource() { cout << "Created"; }
~Resource() { cout << "Destroyed"; }
};
auto res = make_unique<Resource>();unique_ptr value: 42
shared_ptr value: 100
Reference count: 2
After copy, count: 2
Resource acquired
Resource released
make_unique<Type>(value)make_shared<Type>(value)*ptr or ptr->ptr.use_count()Review feedback below