C++ 基础与核心概念

B站影视 内地电影 2025-09-26 04:58 1

摘要:#include int main { std::cout

Node.js 的高性能源于其底层实现,这些模块主要由 C++ 编写。因此,理解 Node.js 底层组成及掌握 C++ 核心概念是深入学习的关键。

Node.js 是基于 Chrome V8 引擎的 JavaScript 运行时,其高效的事件驱动和非阻塞 I/O 能力由以下核心组件实现:

Node.js 底层依赖 C++,以下结合 Node.js 场景讲解 C++ 基础和核心概念。

C++ 是高效的系统级语言,支持过程式、面向对象和泛型编程,注重手动内存管理和性能。

#include int main { std::cout 头文件 : #include 引入库, std:: 是标准命名空间。main 函数 :程序入口。编译 : g++ hello.cpp -o hello && ./hello .

C++ 是强类型语言:

整数: int 、 long .浮点: float 、 double .字符: char .布尔: bool .int age = 25double pi = 3.14159char grade = 'A'bool isNodeDeveloper = trueconst int MAX_AGE = 100 enum Color { RED, GREEN, BLUE } Color myColor = RED

V8 用 double 表示 JS Number。

条件: if-else 、 switch .循环: for 、 while .int main { int n = 10 long long fib[10] fib[0] = 0 fib[1] = 1 for (int i = 2 fib[i] = fib[i-1] + fib[i-2] } for (int i = 0 std::cout int add(int a, int b) { return a +}int main { std::cout

Node.js 扩展用 C++ 函数定义导出方法。

C++ 的面向对象编程(OOP)是其核心特性,支持封装、继承、多态和抽象,广泛用于 Node.js 底层(如 V8 的 Isolate 和 Context )。

封装通过类将数据和方法绑定,访问控制( public 、private 、protected )保护数据。

#include # include class Person { private: std::string name; int age; public: Person(std::string n, int a) : name(n), age(a) {} void setName(std::string n) { name = n; } std::string getName const { return name; } void greet const { std::cout

继承允许子类复用父类代码,支持代码重用和层次结构。

#include # include class Person { protected: std::string name; public: Person(std::string n) : name(n) {} virtual void greet const { std::cout virtual 和 override :支持多态,子类可重写父类虚函数。应用 :V8 的对象层次结构(如 v8::Value 的子类 v8::Object 、 v8::Function )。

多态通过虚函数和指针/引用实现运行时行为动态选择。

#include class Shape { public: virtual double area const = 0; virtual ~Shape = default; };class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double area const override { return 3.14159 *};int main { Shape* shape = new Circle(5.0); std::cout area 应用 :V8 的多态类(如 v8::Value )处理不同 JS 类型。

纯虚函数定义接口,强制子类实现。

#include class Printable { public: virtual void print const = 0; virtual ~Printable = default; };class Document : public Printable { public: void print const override { std::cout print; delete doc; return 0; }应用 :libuv 的句柄(如 uv_handle_t )通过抽象类定义通用接口。#include int main { int x = 10; int* ptr = &x; std::cout int arr[3] = {1, 2, 3};int*for (int i = 0; i

Node.js 的 Buffer 是 char* 指针数组。

int* dynamicPtr = new int*dynamicPtr = 42std::cout #include # include struct Node { int data; Node(int d) : data(d) { std::cout ptr1 = std::make_shared(42); std::cout data

V8 的 v8::Persistent 使用类似机制。

空指针:访问 nullptr 崩溃。野指针:释放后未置空。越界:访问数组边界外。#include int main { int x = 10; int& ref = x; ref = 20; std::cout 应用 :V8 的 v8::Local 传递对象,N-API 用引用管理回调。int* createArray(int size) { int* arr = new int[size]; for (int i = 0; i

资源获取即初始化,libuv 的句柄基于此。

#include template T max(T a, T b) { return a > b ? a : b; }int main { std::cout #include # include template class Box { T value; public: Box(T v) : value(v) {} T getValue const { return value; } };int main { Box intBox(42); Box strBox("Node.js"); std::cout 应用 :V8 的 v8::Local ,libuv 平台抽象。#include # include void worker { std::cout #include # include # include std::mutex mtx; int counter = 0;void increment { for (int i = 0; i lock(mtx); ++counter; } }int main { std::thread t1(increment); std::thread t2(increment); t1.join; t2.join; std::cout 应用 :libuv 线程池,Node.js Worker Threads。#include # include double divide(double a, double b) { if (b == 0) { throw std::runtime_error("Division by zero!"); } return a / b; }int main { try { std::cout 应用 :V8 的 v8::TryCatch ,N-API 错误传递。#include # include # include # include int main { std::vector vec = {1, 2, 3}; vec.push_back(4); for (int x : vec) { std::cout scores; scores["Alice"] = 90; scores["Bob"] = 85; for (const auto& pair : scores) { std::cout #include # include # include int main { std::vector vec = {4, 2, 5, 1, 3}; std::sort(vec.begin, vec.end); for (int x : vec) { std::cout 功能 :微软跨平台 C++ 库管理器。安装 :git clone https://github.com/microsoft/vcpkg.gitcd vcpkg./bootstrap-vcpkg.sh.\bootstrap-vcpkg.bat./vcpkg integrate installvcpkg install v8CMake 集成: find_package(V8) .git clone https://chromium.googlesource.com/v8/v8.gitcd v8git checkout tools/dev/v8gen.py x64.release ninja -C out.gn/x64.releasegit clone https://github.com/libuv/libuv.gitcd libuvmkdir build && cd buildcmake .. -DBUILD_TESTING=OFFmake && make install

执行 JS 代码:

#include # include # include int main { v8::V8::InitializeICU; auto platform = v8::platform::NewDefaultPlatform; v8::V8::InitializePlatform(platform.get); v8::V8::Initialize;v8::Isolate::Createparams create_params; create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator; v8::Isolate* isolate = v8::Isolate::New(create_params);{ v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope context_scope(context);v8::Local source = v8::String::NewFromUtf8(isolate, "'Hello, V8!'").ToLocalChecked; v8::Local script = v8::Script::Compile(context, source).ToLocalChecked; v8::Local result = script->Run(context).ToLocalChecked;v8::String::Utf8Value utf8(isolate, result); std::cout Dispose; v8::V8::Dispose; v8::V8::DisposePlatform; delete create_params.array_buffer_allocator; return 0; }编译 : g++ -I$vcpkg/installed/x64-linux/include -L$vcpkg/installed/x64-linux/lib v8_example.cpp -lv8_monolith -o v8_example .#include # include void timer_cb(uv_timer_t* handle) { std::cout loop); }int main { uv_loop_t* loop = uv_default_loop; uv_timer_t timer; uv_timer_init(loop, &timer); uv_timer_start(&timer, timer_cb, 1000, 0); uv_run(loop, UV_RUN_DEFAULT); uv_loop_close(loop); return 0; }编译 : g++ -I$vcpkg/installed/x64-linux/include -L$vcpkg/installed/x64-linux/lib libuv_timer.cpp -luv -o libuv_timer .

以下是一个使用 libuv 实现简单异步 HTTP 服务器的示例。它基于事件循环监听 TCP 连接,接收请求后返回固定 HTTP 响应("Hello World!"),展示 libuv 的异步非阻塞 I/O 能力。

#include # include # include # define DEFAULT_PORT 7000#define DEFAULT_BACKLOG 128uv_loop_t *loop;void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { buf->base = (char*) malloc(suggested_size); buf->len = suggested_size; }void on_close(uv_handle_t *handle) { free(handle); }void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) { if (nread base); return; }const char *response = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World!"; uv_write_t *req = (uv_write_t *) malloc(sizeof(uv_write_t)); uv_buf_t wrbuf = uv_buf_init((char*)response, strlen(response)); uv_write(req, client, &wrbuf, 1, NULL);uv_close((uv_handle_t*) client, on_close); free(buf->base); }void on_new_connection(uv_stream_t *server, int status) { if (status 说明 :服务器监听 7000 端口,接受连接后读取数据,并返回简单 HTTP 响应。使用 libuv 的事件循环实现异步处理,支持并发连接而非阻塞。编译 : g++ -I$vcpkg/installed/x64-linux/include -L$vcpkg/installed/x64-linux/lib libuv_http_server.cpp -luv -o libuv_http_server .运行 : ./libuv_http_server ,然后用浏览器访问 http://localhost:7000 测试。

本文介绍了 Node.js 的底层组成(V8、libuv 等)、C++ 核心概念(新增面向对象编程能力)、C++ 包管理器及 V8/libuv 安装方法,并使用 libuv 实现简单异步 Web 服务器的示例。

来源:墨码行者

相关推荐