Master move semantics, multithreading, and modern C++ resource management.
Write efficient, concurrent, and resource-safe C++ code.
int x = 10; // x is lvalue (has address)
int y = x + 5; // x+5 is rvalue (temporary)
int&& rref = 20; // rvalue reference to temporarystring s1 = "Hello";
string s2 = std::move(s1); // s1's data moved to s2
// s1 is now in valid but unspecified stateclass Buffer {
int* data;
size_t size;
public:
// Move constructor
Buffer(Buffer&& other) noexcept
: data(other.data), size(other.size) {
other.data = nullptr;
other.size = 0;
}
// Move assignment
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data;
data = other.data;
size = other.size;
other.data = nullptr;
other.size = 0;
}
return *this;
}
};Original: Hello World
After move, s2: Hello World
s1 is now empty
Move constructor called
Move assignment called
T(T&& other) noexceptstd::move(obj)noexcept for move operationsReview feedback below
#include <thread>void task() {
cout << "Running in thread" << endl;
}
thread t(task); // Start thread
t.join(); // Wait for completionthread t([]() {
cout << "Lambda thread" << endl;
});
t.join();void greet(string name) {
cout << "Hello, " << name << endl;
}
thread t(greet, "World");
t.join();#include
mutex mtx;
void safe_print(int id) {
lock_guard lock(mtx);
cout << "Thread " << id << endl;
} Main thread starting
Worker thread running
Thread ID: 12345
Counter value: 1000
All threads complete
thread t(function, args...);t.join();t.detach();lock_guard<mutex> lock(mtx);Review feedback below
class FileHandle {
FILE* file;
public:
FileHandle(const char* name, const char* mode) {
file = fopen(name, mode);
if (!file) throw runtime_error("Cannot open");
}
~FileHandle() {
if (file) fclose(file);
cout << "File closed automatically" << endl;
}
// Disable copying
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
};class Timer {
chrono::time_point start;
string name;
public:
Timer(string n) : name(n),
start(chrono::high_resolution_clock::now()) {}
~Timer() {
auto end = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast(end - start);
cout << name << " took " << duration.count() << "ms" << endl;
}
}; Resource acquired
Using resource...
Resource released automatically
Timer: Operation took 100ms
T(const T&) = delete;{ } to control lifetimeReview feedback below