C++ Snippets
Modern C++ programming features and patterns
Smart Pointers
cppModern C++ memory management
#include <memory>
#include <iostream>
class Resource {
public:
Resource() { std::cout << "Resource acquired\n"; }
~Resource() { std::cout << "Resource destroyed\n"; }
void use() { std::cout << "Resource used\n"; }
};
void uniquePtrExample() {
// Unique ownership
std::unique_ptr<Resource> res1 =
std::make_unique<Resource>();
res1->use();
// Transfer ownership
std::unique_ptr<Resource> res2 = std::move(res1);
res2->use();
// res1 is now nullptr
}
void sharedPtrExample() {
// Shared ownership
std::shared_ptr<Resource> res1 =
std::make_shared<Resource>();
{
std::shared_ptr<Resource> res2 = res1;
std::cout << "Count: " << res1.use_count() << "\n";
res2->use();
} // res2 is destroyed, but resource lives on
res1->use();
} // resource is destroyed when last reference is goneTemplates
cppGeneric programming in C++
#include <iostream>
#include <type_traits>
// Function template
template<typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
// Class template
template<typename T, size_t N>
class Array {
private:
T data[N];
public:
constexpr size_t size() const { return N; }
T& operator[](size_t index) {
return data[index];
}
const T& operator[](size_t index) const {
return data[index];
}
};
// Template specialization
template<typename T>
class SmartPtr {
public:
explicit SmartPtr(T* ptr) : ptr_(ptr) {}
~SmartPtr() { delete ptr_; }
T& operator*() { return *ptr_; }
T* operator->() { return ptr_; }
private:
T* ptr_;
};
// Partial specialization for arrays
template<typename T>
class SmartPtr<T[]> {
public:
explicit SmartPtr(T* ptr) : ptr_(ptr) {}
~SmartPtr() { delete[] ptr_; }
T& operator[](size_t index) { return ptr_[index]; }
private:
T* ptr_;
};Modern C++ Features
cppC++17/20 language features
#include <optional>
#include <variant>
#include <string>
#include <iostream>
// Structured bindings
struct Point {
int x;
int y;
};
void structuredBindings() {
Point p{1, 2};
auto [x, y] = p;
std::cout << x << ", " << y << "\n";
}
// Optional values
std::optional<std::string> parseString(bool valid) {
if (valid) {
return "Valid string";
}
return std::nullopt;
}
// Variant type
using Variant = std::variant<int, float, std::string>;
void processVariant(const Variant& v) {
std::visit([](const auto& value) {
std::cout << value << "\n";
}, v);
}
// Concepts (C++20)
#if __cplusplus >= 202002L
template<typename T>
concept Numeric = std::is_arithmetic_v<T>;
template<Numeric T>
T add(T a, T b) {
return a + b;
}
#endifSTL Algorithms
cppStandard Template Library algorithms
#include <vector>
#include <algorithm>
#include <numeric>
#include <iostream>
void stlAlgorithms() {
std::vector<int> v = {4, 1, 3, 5, 2};
// Sorting
std::sort(v.begin(), v.end());
// Binary search
bool found = std::binary_search(v.begin(), v.end(), 3);
// Finding elements
auto it = std::find_if(v.begin(), v.end(),
[](int n) { return n > 3; });
// Transforming elements
std::vector<int> squared;
std::transform(v.begin(), v.end(),
std::back_inserter(squared),
[](int n) { return n * n; });
// Accumulate
int sum = std::accumulate(v.begin(), v.end(), 0);
// Partition
auto pivot = std::partition(v.begin(), v.end(),
[](int n) { return n % 2 == 0; });
// Remove elements
v.erase(std::remove_if(v.begin(), v.end(),
[](int n) { return n < 3; }), v.end());
}