本体论如何赋能数据科学:以疫情建模为例
2026/7/19 20:29:49
C++ 是一门广泛应用于高性能计算、游戏开发、嵌入式系统和底层系统编程的语言。其核心优势在于对内存的精细控制和接近硬件的操作能力。以下是围绕你提供的“核心学习路径”进行的详细解析与实战示例。
inta=10;doubleb=3.14;charc='A';boolflag=true;intx=5;int*ptr=&x;// 指针指向x的地址int&ref=x;// 引用,ref是x的别名(*ptr)++;// x变为6ref++;// x变为7if(a>5){cout<<"a is greater than 5\n";}else{cout<<"a is not greater than 5\n";}for(inti=0;i<5;++i){cout<<i<<" ";}classAnimal{public:virtualvoidspeak(){cout<<"Animal speaks\n";}};classDog:publicAnimal{public:voidspeak()override{cout<<"Woof!\n";}// 多态实现};// 使用Animal*pet=newDog();pet->speak();// 输出: Woof!deletepet;#include<vector>#include<map>#include<iostream>usingnamespacestd;// vector 示例vector<int>nums={3,1,4,1,5};sort(nums.begin(),nums.end());// 排序后: 1,1,3,4,5// map 示例map<string,int>ages;ages["Alice"]=25;ages["Bob"]=30;for(auto&pair:ages){cout<<pair.first<<": "<<pair.second<<endl;}int*p=newint(42);// 动态分配一个整数cout<<*p<<endl;// 输出 42deletep;// 释放内存// 数组版本int*arr=newint[10];for(inti=0;i<10;++i)arr[i]=i*i;delete[]arr;// 注意使用 delete[]⚠️ 现代 C++ 推荐使用智能指针(如
unique_ptr,shared_ptr)避免手动管理内存。
#include<iostream>usingnamespacestd;voidquickSort(intarr[],intlow,inthigh){if(low>=high)return;intpivot=arr[(low+high)/2];intleft=low,right=high;while(left<=right){while(arr[left]<pivot)left++;while(arr[right]>pivot)right--;if(left<=right){swap(arr[left],arr[right]);left++;right--;}}quickSort(arr,low,right);quickSort(arr,left,high);}intmain(){intdata[]={64,34,25,12,22,11,90};intn=sizeof(data)/sizeof(data[0]);quickSort(data,0,n-1);for(inti=0;i<n;++i)cout<<data[i]<<" ";return0;}#include<iostream>#include<cstdlib>#include<ctime>usingnamespacestd;intmain(){srand(time(0));intsecret=rand()%100+1;intguess;cout<<"Guess the number (1-100): ";while(cin>>guess){if(guess==secret){cout<<"Congratulations! You guessed it!\n";break;}elseif(guess<secret){cout<<"Too low! Try again: ";}else{cout<<"Too high! Try again: ";}}return0;}在现代 C++(尤其是 C++11 及以后标准)中,推荐使用智能指针来自动管理动态内存,避免手动调用new和delete导致的内存泄漏、重复释放或异常安全问题。最常用的智能指针是std::unique_ptr和std::shared_ptr。
std::unique_ptr:独占所有权unique_ptr拥有。unique_ptr离开作用域时,自动释放其所指向的对象。#include<iostream>#include<memory>// 必须包含头文件classMyClass{public:MyClass(){std::cout<<"MyClass constructed\n";}~MyClass(){std::cout<<"MyClass destructed\n";}voidsayHello(){std::cout<<"Hello from MyClass!\n";}};intmain(){// 创建 unique_ptrstd::unique_ptr<MyClass>ptr=std::make_unique<MyClass>();ptr->sayHello();// 使用 -> 调用成员函数// 自动析构:当 main 结束时,ptr 被销毁,对象自动删除return0;}✅ 输出:
MyClass constructed Hello from MyClass! MyClass destructedautoptr1=std::make_unique<MyClass>();// auto ptr2 = ptr1; // 错误!不能复制autoptr2=std::move(ptr1);// 正确:转移所有权// 此时 ptr1 为空,ptr2 拥有对象std::shared_ptr:共享所有权shared_ptr可以共享同一个对象。shared_ptr,计数 +1;减少则 -1。#include<iostream>#include<memory>intmain(){// 创建 shared_ptrstd::shared_ptr<MyClass>ptr1=std::make_shared<MyClass>();{std::shared_ptr<MyClass>ptr2=ptr1;// 共享所有权std::cout<<"Reference count: "<<ptr1.use_count()<<"\n";// 输出 2}// ptr2 离开作用域,计数减为 1std::cout<<"Reference count: "<<ptr1.use_count()<<"\n";// 输出 1return0;// 此时 ptr1 析构,计数变为0,对象被删除}✅ 输出:
MyClass constructed Reference count: 2 Reference count: 1 MyClass destructed| 推荐方式 | 说明 |
|---|---|
std::make_unique<T>() | C++14 起支持,安全创建unique_ptr |
std::make_shared<T>() | 高效创建shared_ptr,建议优先使用 |
⚠️不要这样写:
// ❌ 危险:可能造成内存泄漏(异常中断)std::function<void()>f(newMyClass(),[](MyClass*p){deletep;});// 如果 new MyClass() 成功,但在构造函数后抛出异常,资源将未被管理✅ 应该使用make_unique/make_shared来避免此类问题。
| 场景 | 推荐智能指针 |
|---|---|
| 工厂模式返回对象 | std::unique_ptr<Base> |
| 树节点中的父/子关系(避免循环引用) | 子用std::weak_ptr,父用std::shared_ptr |
| 多个对象共享同一资源(如缓存) | std::shared_ptr |
| 临时动态对象(如局部对象) | std::unique_ptr |
shared_ptr循环引用(例如 A 指向 B,B 又指向 A),会导致内存无法释放。std::weak_ptr解决循环引用问题。weak_ptr解法structNode;usingNodePtr=std::shared_ptr<Node>;usingWeakNode=std::weak_ptr<Node>;structNode{intid;WeakNode parent;// 使用 weak_ptr 避免循环引用Node(inti):id(i){std::cout<<"Node "<<id<<" created\n";}~Node(){std::cout<<"Node "<<id<<" destroyed\n";}};RAII(Resource Acquisition Is Initialization,资源获取即初始化)是 C++ 中一种重要的编程范式,其核心思想是:
将资源的生命周期绑定到对象的生命周期上—— 资源在对象构造时获取,在对象析构时自动释放。
这里的“资源”不仅指内存,还包括文件句柄、网络连接、互斥锁、数据库连接等任何需要申请和释放的系统资源。
#include<fstream>#include<iostream>classFileHandler{std::ofstream file;public:FileHandler(conststd::string&filename){file.open(filename);if(!file.is_open()){throwstd::runtime_error("Cannot open file!");}std::cout<<"File opened: "<<filename<<"\n";}voidwrite(conststd::string&data){file<<data<<std::endl;}~FileHandler(){if(file.is_open()){file.close();std::cout<<"File closed.\n";}}};intmain(){try{FileHandlerfh("output.txt");fh.write("Hello, RAII!");// 离开作用域时自动关闭文件,无需手动调用 close()}catch(conststd::exception&e){std::cerr<<e.what()<<std::endl;}return0;}即使中间发生异常,C++ 的栈展开机制也会调用局部对象的析构函数,从而保证资源被正确释放。
std::unique_ptr和std::shared_ptr就是基于 RAII 原则设计的经典工具:
| 特性 | 如何体现 RAII |
|---|---|
| 构造时分配内存 | 在make_unique或new时获取堆内存 |
| 析构时释放内存 | 离开作用域时自动调用delete或delete[] |
| 异常安全 | 即使抛出异常,栈上智能指针仍会析构,防止内存泄漏 |
❌ 手动管理容易出错:
voidbad_example(){MyClass*ptr=newMyClass();do_something();// 如果这里抛出异常deleteptr;// 这行不会执行 → 内存泄漏!}✅ 使用 RAII 自动管理:
voidgood_example(){autoptr=std::make_unique<MyClass>();do_something();// 即使抛出异常,ptr 析构时自动释放内存}// 自动 deletedelete或close()。std::lock_guard)std::mutex mtx;voidthread_safe_func(){std::lock_guard<std::mutex>lock(mtx);// 构造时加锁// 操作共享数据// 析构时自动解锁,即使发生异常也安全}比如数据库连接、图形上下文等都可以封装成 RAII 类型。