在 Ubuntu 下使用 C++ 智能指针,本质上就是 使用 C++11 及以后标准库中的 <memory>。下面从环境准备 → 常见智能指针 → 示例 → 注意事项逐步说明。
sudo apt update
sudo apt install g++ -y
检查版本(建议 ≥ 7):
g++ --version
g++ main.cpp -std=c++11 -o main
推荐使用:
g++ main.cpp -std=c++17 -o main
C++ 标准库提供三种主要智能指针:
| 智能指针 | 说明 |
|---|---|
std::unique_ptr |
独占所有权(最常用) |
std::shared_ptr |
引用计数,共享所有权 |
std::weak_ptr |
配合 shared_ptr,防止循环引用 |
#include <iostream>
#include <memory>
using namespace std;
int main() {
unique_ptr<int> p = make_unique<int>(10);
cout << *p << endl;
return 0;
}
class A {
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
};
int main() {
unique_ptr<A> a = make_unique<A>();
}
unique_ptr<A> p1 = make_unique<A>();
unique_ptr<A> p2 = move(p1); // p1 变为 nullptr
shared_ptr<int> p1 = make_shared<int>(20);
shared_ptr<int> p2 = p1; // 引用计数 +1
cout << p1.use_count() << endl; // 2
shared_ptr<FILE> file(
fopen("test.txt", "r"),
fclose
);
struct B;
struct A {
shared_ptr<B> b;
};
struct B {
shared_ptr<A> a;
};
⚠ 会导致内存泄漏。
struct B;
struct A {
shared_ptr<B> b;
};
struct B {
weak_ptr<A> a;
};
#include <iostream>
#include <memory>
using namespace std;
class Test {
public:
Test() { cout << "Test()" << endl; }
~Test() { cout << "~Test()" << endl; }
};
int main() {
auto p = make_unique<Test>();
auto sp = make_shared<Test>();
return 0;
}
编译运行:
g++ main.cpp -std=c++17 -o main
./main
✅ 优先使用 unique_ptr
✅ 需要共享时才用 shared_ptr
❌ 不要用 new + 原始指针
❌ 不要混用原始指针和智能指针
如果你愿意,我可以:
直接告诉我你的使用场景即可。