三分钟读完《Essential C++》

发布时间 2023-09-12 18:04:00作者: 杜jn
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <tuple>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>

#ifdef __cplusplus

#if __cplusplus <= 201103L
namespace std {
    template<typename T, typename... Args>
    std::unique_ptr<T> make_unique(Args&&... args) {
        return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
    }
}
#endif

#endif


// 规则1: 避免使用宏定义
// 不使用宏定义

// 规则2: 使用const来限制变量的修改
const int MAX_VALUE = 100;

// 规则3: 使用引用传递参数
void modifyValue(int& value) {
    value = 42;
}

// 规则4: 使用C++风格的类型转换
int intValue = static_cast<int>(3.14);

// 规则5: 使用const成员函数
class MyClass {
public:
    void modifyData() {
        data_ = 42;
    }

    int getData() const {
        return data_;
    }

private:
    int data_;
};

// 规则6: 尽量使用初始化列表
class AnotherClass {
public:
    AnotherClass(int value) : value_(value) {}

private:
    int value_;
};

// 规则7: 避免使用裸指针
std::unique_ptr<int> createIntPtr() {
    return std::make_unique<int>(42);
}

// 规则8: 使用std::string代替C风格字符串
std::string str = "Hello, world!";

// 规则9: 使用std::vector代替数组
std::vector<int> numbers = {1, 2, 3, 4, 5};

// 规则10: 使用std::array或std::vector代替C风格数组
std::array<int, 3> arr = {1, 2, 3};

// 规则11: 使用std::unique_ptr或std::shared_ptr管理动态内存
std::unique_ptr<int> ptr = std::make_unique<int>(42);

// 规则12: 使用范围for循环
void printNumbers(const std::vector<int>& nums) {
    for (const auto& num : nums) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}

// 规则13: 避免使用goto语句
void someFunction() {
    bool condition = true;
    if (condition) {
        // do something
    } else {
        // do something else
    }
}

// 规则14: 使用自定义类型代替布尔型标志
enum class Status { OK, ERROR };

// 规则15: 将多个相关变量组织成结构体或类
struct Person {
    std::string name;
    int age;
};

// 规则16: 避免跨文件的全局变量
namespace {
    int internalVariable = 42;
}

// 规则17: 使用enum class代替enum
enum class Color { RED, GREEN, BLUE };

// 规则18: 将类的成员函数定义和声明分离
class MyClass2 {
public:
    void memberFunction(); // 在类的声明中只声明函数

private:
    int data_;
};

void MyClass2::memberFunction() {
    // 在类的定义中实现函数
}

// 规则19: 使用虚函数实现多态
class Base {
public:
    virtual void doSomething() {
        std::cout << "Base::doSomething()" << std::endl;
    }
};

class Derived : public Base {
public:
    void doSomething() override {
        std::cout << "Derived::doSomething()" << std::endl;
    }
};

// 规则20: 使用override关键字显式地重写虚函数
class Base2 {
public:
    virtual void doSomething() {
        std::cout << "Base2::doSomething()" << std::endl;
    }
};

class Derived2 : public Base2 {
public:
    void doSomething() override {
        std::cout << "Derived2::doSomething()" << std::endl;
    }
};

// 规则21: 使用final关键字禁止继承
class Base3 final {
public:
    virtual void doSomething() {
        std::cout << "Base3::doSomething()" << std::endl;
    }
};

// 规则22: 使用默认成员初始化
class MyClass3 {
public:
    MyClass3() = default; // 使用默认构造函数
    MyClass3(int value) : value_(value) {}

private:
    int value_ = 0; // 使用默认成员初始化
};

// 规则23: 使用std::initializer_list进行初始化
class MyClass4 {
public:
    MyClass4(std::initializer_list<int> values) {
        for (int value : values) {
            values_.push_back(value);
        }
    }

private:
    std::vector<int> values_;
};

// 规则24: 使用拷贝控制成员函数
class MyClass5 {
public:
    MyClass5(const MyClass5& other) {
        // 拷贝构造函数
    }

    MyClass5& operator=(const MyClass5& other) {
        if (this != &other) {
            // 拷贝赋值运算符
        }
        return *this;
    }

    ~MyClass5() {
        // 析构函数
    }
};

// 规则25: 使用移动语义提高性能
class MyClass6 {
public:
    MyClass6(MyClass6&& other) noexcept {
        // 移动构造函数
    }

    MyClass6& operator=(MyClass6&& other) noexcept {
        if (this != &other) {
            // 移动赋值运算符
        }
        return *this;
    }
};

// 规则26: 使用RAII资源管理
class File {
public:
    explicit File(const std::string& filename) {
        // 打开文件
    }

    ~File() {
        // 关闭文件
    }

    // 其他成员函数
};

// 规则27: 使用智能指针进行资源管理
void manageResource() {
    std::shared_ptr<int> ptr = std::make_shared<int>(42);
    // 使用智能指针ptr
}

// 规则28: 使用标准库容器进行数据管理
void manageData() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    // 使用numbers进行数据管理
}

// 规则29: 使用std::function实现函数对象
int add(int a, int b) {
    return a + b;
}

std::function<int(int, int)> func = add;

// 规则30: 使用Lambda表达式实现匿名函数
auto f30 = [](){
    std::vector<int> nums = {1, 2, 3, 4, 5};
    int sum = 0;
    std::for_each(nums.begin(), nums.end(), [&](int num) {
        sum += num;
    });
};

// 规则31: 使用std::algorithm进行常见操作
std::vector<int> nums2 = {1, 2, 3, 4, 5};
int max = *std::max_element(nums2.begin(), nums2.end());

// 规则32: 使用异常处理错误
void process() {
    try {
        // 可能引发异常的代码
    } catch (const std::exception& e) {
        // 异常处理代码
    }
}

// 规则33: 使用异常规范声明函数可能抛出的异常
void func2() noexcept {
    // 不会抛出异常的函数
}

// 规则34: 使用std::mutex和std::lock_guard进行互斥访问
std::mutex mtx;
int sharedData = 0;

void updateSharedData() {
    std::lock_guard<std::mutex> lock(mtx);
    // 更新共享数据
}

// 规则35: 使用std::condition_variable进行线程同步
std::mutex mtx2;
std::condition_variable cv;
bool ready = false;

void waitForSignal() {
    std::unique_lock<std::mutex> lock(mtx2);
    cv.wait(lock, [] { return ready; });
    // 执行等待后的操作
}

void sendSignal() {
    std::lock_guard<std::mutex> lock(mtx2);
    ready = true;
    cv.notify_one();
}

// 规则36: 使用std::atomic进行原子操作
std::atomic<int> atomicValue{0};

void incrementAtomicValue() {
    atomicValue++;
}

// 规则37: 避免使用未定义行为
auto p37 = [](){
int x = 5;
int y = 0;
int result = x / y; // 未定义行为:除以0
};

// 规则38: 避免使用强制类型转换
double d = 3.14;
int i = static_cast<int>(d);

// 规则39: 使用命名空间进行组织和避免命名冲突
namespace MyNamespace {
    int value = 42;
}

// 规则40: 使用头文件保护
#ifndef MY_HEADER_H
#define MY_HEADER_H

// 头文件的内容

#endif

// 规则41: 避免滥用宏定义
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int maxValue = MAX(5, 10);

// 规则42: 使用迭代器进行数据遍历和操作
auto f42=[](){
    std::vector<int> numbers2 = {1, 2, 3, 4, 5};
    for (auto it = numbers2.begin(); it != numbers2.end(); ++it) {
        *it *= 2;
    }
};

// 规则43: 使用合适的容器选择算法
auto f43 = [](){
    std::vector<int> numbers3 = {1, 2, 3, 4, 5};
    std::sort(numbers3.begin(), numbers3.end());
};

// 规则44: 使用关联容器进行高效查找
auto f44 = [](){
std::map<std::string, int> scores = {{"Alice", 100}, {"Bob", 90}};
int aliceScore = scores["Alice"];
};

// 规则45: 使用std::tuple进行多值组合
std::tuple<std::string, int, double> data = std::make_tuple("Alice", 25, 3.14);
std::string name = std::get<0>(data);
int age = std::get<1>(data);
double value = std::get<2>(data);

// 规则46: 使用std::pair进行键值对存储
std::pair<std::string, int> student = {"Alice", 25};
std::string studentName = student.first;
int studentAge = student.second;

// 规则47: 使用std::set进行排序和去重
auto f47 = [](){
    std::set<int> uniqueNumbers = {2, 1, 3, 2, 4, 3, 5, 1};
    for (int num : uniqueNumbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
};

// 规则48: 使用std::map进行键值映射
std::map<std::string, int> ageMap = {{"Alice", 25}, {"Bob", 30}};
int aliceAge = ageMap["Alice"];

// 规则49: 使用std::unordered_set进行高效查找
std::unordered_set<int> numberSet = {1, 2, 3, 4, 5};
bool containsThree = numberSet.find(3) != numberSet.end();

// 规则50: 使用std::unordered_map进行高效键值映射
std::unordered_map<std::string, int> scoreMap = {{"Alice", 100}, {"Bob", 90}};
int aliceScore2 = scoreMap["Alice"];

// 规则51: 使用智能指针管理资源
std::shared_ptr<int> ptr2 = std::make_shared<int>(42);
// 使用智能指针ptr2

// 规则52: 使用std::reference_wrapper进行引用传递
void modifyValue(std::reference_wrapper<int> valueRef) {
    valueRef.get() = 42;
}

auto f52 = [](){
    int refValue = 10;
    modifyValue(refValue);
};

// 规则53: 使用std::tie进行元组解包
auto f53 = [](){
    std::tuple<std::string, int, double> studentData = std::make_tuple("Alice", 25, 3.14);
    std::string name2;
    int age2;
    double value2;
    std::tie(name2, age2, value2) = studentData;
};

// 规则54: 使用std::enable_if进行模板条件编译
template <typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type addOne(T value) {
    return value + 1;
}

// 规则55: 避免使用裸new和delete
std::unique_ptr<int> dynamicInt = std::make_unique<int>(42);

int main() {
    return 0;
}