Modern C++ utilizes features introduced in C++11 and later versions (C++14, C++17, C++20, etc.) to write cleaner, more efficient, and more maintainable code. Here are some best practices and examples to follow for Modern C++:
With auto, the compiler deduces the type of the variable, making code simpler and reducing redundancy.
auto x = 10; // x is deduced to be int
auto y = 5.0; // y is deduced to be doublenullptr is a type-safe null pointer introduced in C++11.
int* ptr = nullptr;Range-based for loops simplify iteration over containers.
std::vector<int> vec = {1, 2, 3, 4, 5};
for (const auto& elem : vec) {
std::cout << elem << " ";
}Smart pointers handle automatic memory management and help avoid memory leaks.
#include <memory>
std::unique_ptr<int> p1(new int(5)); // unique_ptr
std::shared_ptr<int> p2 = std::make_shared<int>(10); // shared_ptrFor creating threads, std::thread provides a clearer and safer API.
#include <thread>
void threadFunction() {
// Do some work
}
std::thread t(threadFunction);
t.join(); // Wait for the thread to finishconstexpr can be used to perform computations at compile time.
constexpr int square(int x) {
return x * x;
}
int area = square(5); // Computed at compile timeenum class offers better type safety.
enum class Color { Red, Green, Blue };
Color c = Color::Red;Leverage default comparison operators where == and != can be synthesized by the compiler in newer C++ versions.
struct Point {
int x, y;
auto operator<=>(const Point&) const = default; // Adds all comparison operators
};std::array provides the benefits of a statically-sized array with improved safety and functionality.
#include <array>
std::array<int, 5> nums = {1, 2, 3, 4, 5};std::optional represents optional values that may or may not exist.
#include <optional>
std::optional<int> getValue(bool condition) {
if (condition) return 42;
else return std::nullopt;
}-
Books:
- "Effective Modern C++" by Scott Meyers
- "C++ Primer (5th Edition)" by Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo
-
Online Courses:
- C++ Nanodegree Program by Udacity
- C++ Fundamentals by Pluralsight
-
Online Documentation and Tutorials:
- cppreference.com: A comprehensive online resource for C++ standard library documentation.
- cplusplus.com: Another widely-used resource for C++ documentation and tutorials.
-
Video Tutorials:
- C++ Programming Playlist by The Cherno
- C++ Weekly: Weekly video series on Modern C++ features and best practices.
By adhering to these best practices and using the suggested resources, you can significantly improve your proficiency in Modern C++.