专业编程基础技术教程

网站首页 > 基础教程 正文

JS程序员学C++入门教程(下篇)

ccvgpt 2025-04-26 17:04:54 基础教程 1 ℃

1. 模板与泛型编程

JavaScript (动态类型处理)

// JS 函数天然支持任意类型参数
function identity(x) {
    return x;
}
console.log(identity(10));    // 10
console.log(identity("text"));// "text"

C (宏实现泛型)

// 使用宏模拟泛型
#define IDENTITY(x) (x)

int main() {
    int a = IDENTITY(10);
    char* s = IDENTITY("text");
    // 无类型安全检查
}

C++ (类型安全模板)

template <typename T>
T identity(T x) {
    return x;
}

int main() {
    auto a = identity(10);     // 推导为 int
    auto b = identity("text"); // 推导为 const char*
    // 编译时生成特化版本
}

JS 注意

  1. C++ 模板在编译时实例化(JS 运行时处理)
  2. 模板错误信息复杂,需逐步调试

2. 智能指针(C++11+)

JavaScript (自动 GC)

class FileHandle {
    constructor() { this.resource = acquireResource(); }
    // 无需手动释放,GC 自动回收
}

let fh = new FileHandle();
fh = null; // 资源最终被回收

C (原始指针)

typedef struct {
    FILE* handle;
} FileHandle;

FileHandle* createFile() {
    FileHandle* fh = malloc(sizeof(FileHandle));
    fh->handle = fopen("test.txt", "r");
    return fh;
}

void closeFile(FileHandle* fh) {
    if (fh) {
        fclose(fh->handle);
        free(fh);
    }
}

// 必须严格手动调用 closeFile

C++ (智能指针)

#include <memory>
class FileWrapper {
public:
    FileWrapper(const std::string& filename) 
        : handle(fopen(filename.c_str(), "r")) {}
    ~FileWrapper() { if (handle) fclose(handle); }
private:
    FILE* handle;
};

int main() {
    // unique_ptr 自动管理生命周期
    auto file = std::make_unique<FileWrapper>("test.txt");
    
    // shared_ptr 引用计数
    auto sharedFile = std::make_shared<FileWrapper>("shared.txt");
    
    // 无需手动释放
}

关键优势

JS程序员学C++入门教程(下篇)

  • unique_ptr 实现独占所有权(类似 Rust)
  • shared_ptr 实现共享所有权(类似 JS 引用计数)
  • 完全避免 delete 操作

3. 移动语义与右值引用

JavaScript (无显式移动语义)

let arr1 = [1,2,3];
let arr2 = arr1; // 复制引用
arr1.push(4);    // arr2 也会变化

C (深拷贝)

struct Vector {
    int* data;
    size_t size;
};

// 必须手动实现深拷贝
struct Vector cloneVector(struct Vector src) {
    struct Vector dest;
    dest.size = src.size;
    dest.data = malloc(dest.size * sizeof(int));
    memcpy(dest.data, src.data, dest.size * sizeof(int));
    return dest;
}

C++ (移动语义)

class Vector {
    int* data;
    size_t size;
public:
    // 移动构造函数
    Vector(Vector&& other) noexcept 
        : data(other.data), size(other.size) {
        other.data = nullptr; // 转移所有权
        other.size = 0;
    }
    
    // 移动赋值运算符
    Vector& operator=(Vector&& other) noexcept {
        delete[] data;
        data = other.data;
        size = other.size;
        other.data = nullptr;
        return *this;
    }
    
    ~Vector() { delete[] data; }
};

int main() {
    Vector v1;
    Vector v2 = std::move(v1); // 调用移动构造
}

性能关键

  • 移动语义避免深拷贝(类似 Rust 所有权转移)
  • 右值引用 (&&) 标识可移动资源

4. Lambda 表达式

JavaScript (箭头函数)

const numbers = [1,2,3];
const squares = numbers.map(x => x * x);
console.log(squares); // [1,4,9]

C (函数指针)

#include <stdio.h>
void map(int* arr, size_t n, int (*f)(int)) {
    for (size_t i=0; i<n; i++) 
        arr[i] = f(arr[i]);
}

int square(int x) { return x*x; }

int main() {
    int arr[] = {1,2,3};
    map(arr, 3, square); // 输出 [1,4,9]
}

C++ (Lambda)

#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers{1,2,3};
    std::transform(numbers.begin(), numbers.end(), numbers.begin(),
        [](int x) { return x * x; } // Lambda 表达式
    );
    
    // 捕获列表示例
    int factor = 2;
    auto multiplier = [factor](int x) { return x * factor; };
}

语法对比

  • [] 捕获列表(类似 JS 闭包捕获变量)
  • C++ Lambda 可转换为函数指针(当不捕获时)

5. 并发编程

JavaScript (事件循环)

// Node.js 异步模型
console.log("Start");
setTimeout(() => console.log("Timeout"), 1000);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
// 输出顺序:Start → End → Promise → Timeout

C (POSIX 线程)

#include <pthread.h>
#include <stdio.h>

void* threadFunc(void* arg) {
    printf("Thread: %d\n", *(int*)arg);
    return NULL;
}

int main() {
    pthread_t tid;
    int arg = 42;
    pthread_create(&tid, NULL, threadFunc, &arg);
    pthread_join(tid, NULL);
    printf("Main thread exit\n");
}

C++ (std::thread)

#include <iostream>
#include <thread>
#include <future>

void worker(int id) {
    std::cout << "Thread " << id << " working\n";
}

int main() {
    std::thread t1(worker, 1);
    auto future = std::async([](){ return 42; }); // 异步任务
    
    t1.join();
    std::cout << "Result: " << future.get() << std::endl;
}

现代特性

  • std::async 实现类似 JS Promise 的异步模式
  • 原子操作 (std::atomic) 解决竞态条件
  • 互斥锁 (std::mutex) 保证线程安全

6. 实战项目

项目1:命令行贪吃蛇游戏

// 使用现代 C++ 特性
#include <ncurses.h>
#include <deque>
#include <chrono>
#include <thread>

class SnakeGame {
    std::deque<std::pair<int,int>> body;
    // 使用智能指针管理资源
    std::unique_ptr<WINDOW, void(*)(WINDOW*)> win;
public:
    SnakeGame() : win(newwin(20,40,0,0), delwin) { /* 初始化 */ }
    void run() { /* 游戏主循环 */ }
};

int main() {
    SnakeGame game;
    game.run();
}

项目2:与 Node.js 集成(N-API)

// native.cpp
#include <napi.h>

Napi::String Hello(const Napi::CallbackInfo& info) {
    return Napi::String::New(info.Env(), "Hello from C++");
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
    exports.Set("hello", Napi::Function::New(env, Hello));
    return exports;
}

NODE_API_MODULE(native, Init)
// app.js
const native = require('./build/Release/native');
console.log(native.hello()); // 输出 "Hello from C++"

现代 C++ 最佳实践

  1. 优先使用:auto 推导类型智能指针替代原始指针constexpr 编译时计算范围 for 循环
  2. 避免:裸 new/deleteC 风格数组(改用 std::array/vector)宏定义常量(改用 const/constexpr)
  3. 性能关键路径:移动语义减少拷贝预分配内存(reserve())使用 noexcept 优化

教程总结

  • 从 JS 到 C++ 的核心转变:类型系统内存控制零成本抽象
  • 现代 C++ 开发范式:RAII + 智能指针 + 模板 + 并发
  • 持续学习方向:模板元编程、协程(C++20)、概念(Concepts)

Tags:

最近发表
标签列表