Loading workspace environment...
Master modern memory management with zero manual `delete` calls using `std::unique_ptr`, `std::shared_ptr`, rvalue references (`&&`), and `std::move`.
auto ptr = std::make_unique<Widget>("arg");Creates uniquely-owned heap object with automatic RAII deallocation.Widget w2 = std::move(w1);Transfers ownership without copying resources.#include <iostream>
#include <memory>
#include <string>
#include <vector>
class DatabaseConnection {
private:
std::string connectionString;
public:
DatabaseConnection(const std::string& conn) : connectionString(conn) {
std::cout << "[Connect] Opened " << connectionString << "\n";
}
~DatabaseConnection() {
std::cout << "[Disconnect] Closed " << connectionString << " automatically via RAII\n";
}
void executeQuery(const std::string& sql) const {
std::cout << " Executing on " << connectionString << ": " << sql << "\n";
}
};
int main() {
std::cout << "--- Entering Scope ---\n";
{
// std::make_unique manages the heap lifetime
auto db = std::make_unique<DatabaseConnection>("postgres://prod-cluster:5432");
db->executeQuery("SELECT * FROM users");
// Move ownership into another unique_ptr
std::unique_ptr<DatabaseConnection> movedDb = std::move(db);
// db is now nullptr, movedDb owns the resource
if (!db) {
std::cout << "[State] Original pointer is now null after std::move\n";
}
movedDb->executeQuery("SELECT COUNT(*) FROM orders");
} // movedDb goes out of scope here -> destructor runs automatically!
std::cout << "--- Exited Scope ---\n";
return 0;
}--- Entering Scope ---
[Connect] Opened postgres://prod-cluster:5432
Executing on postgres://prod-cluster:5432: SELECT * FROM users
[State] Original pointer is now null after std::move
Executing on postgres://prod-cluster:5432: SELECT COUNT(*) FROM orders
[Disconnect] Closed postgres://prod-cluster:5432 automatically via RAII
--- Exited Scope ---Widget* w = new Widget(); // Manual new without RAII risks memory leaks on exceptionsauto w = std::make_unique<Widget>();Architectural Explanation: Avoid raw `new` and `delete`. Use `std::make_unique` and `std::make_shared` for exception-safe memory management.
Write an RAII `ScopedTimer` struct that records the start time in its constructor and prints elapsed milliseconds in its destructor.