温馨提示×

ubuntu c++怎么用智能指针

小樊
41
2026-09-02 08:58:58
栏目: 编程语言

在 Ubuntu 下使用 C++ 智能指针,本质上就是 使用 C++11 及以后标准库中的 <memory>。下面从环境准备 → 常见智能指针 → 示例 → 注意事项逐步说明。


一、Ubuntu 环境准备

1. 安装 g++

sudo apt update
sudo apt install g++ -y

检查版本(建议 ≥ 7):

g++ --version

2. 编译时开启 C++11 或更高标准

g++ main.cpp -std=c++11 -o main

推荐使用:

g++ main.cpp -std=c++17 -o main

二、C++ 常见智能指针

C++ 标准库提供三种主要智能指针:

智能指针 说明
std::unique_ptr 独占所有权(最常用)
std::shared_ptr 引用计数,共享所有权
std::weak_ptr 配合 shared_ptr,防止循环引用

三、unique_ptr(推荐优先使用)

1. 基本用法

#include <iostream>
#include <memory>

using namespace std;

int main() {
    unique_ptr<int> p = make_unique<int>(10);
    cout << *p << endl;
    return 0;
}

2. 管理自定义对象

class A {
public:
    A() { cout << "A()" << endl; }
    ~A() { cout << "~A()" << endl; }
};

int main() {
    unique_ptr<A> a = make_unique<A>();
}

3. 转移所有权

unique_ptr<A> p1 = make_unique<A>();
unique_ptr<A> p2 = move(p1);  // p1 变为 nullptr

四、shared_ptr(共享所有权)

1. 基本用法

shared_ptr<int> p1 = make_shared<int>(20);
shared_ptr<int> p2 = p1;  // 引用计数 +1

cout << p1.use_count() << endl;  // 2

2. 自定义删除器(可选)

shared_ptr<FILE> file(
    fopen("test.txt", "r"),
    fclose
);

五、weak_ptr(解决循环引用)

循环引用问题

struct B;

struct A {
    shared_ptr<B> b;
};

struct B {
    shared_ptr<A> a;
};

⚠ 会导致内存泄漏。

使用 weak_ptr 解决

struct B;

struct A {
    shared_ptr<B> b;
};

struct B {
    weak_ptr<A> a;
};

六、完整示例(Ubuntu 可直接编译)

#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 + 原始指针
❌ 不要混用原始指针和智能指针


如果你愿意,我可以:

  • 给你 Ubuntu + CMake 的智能指针示例
  • 智能指针底层原理
  • 帮你 排查现有代码的内存泄漏问题

直接告诉我你的使用场景即可。

0