C++智能指针通过RAII管理动态内存,避免泄漏与野指针。std::unique_ptr独占所有权,高效无开销,适用于单一所有者场景;std::shared_ptr共享所有权,用引用计数控制生命周期,适合多所有者共享资源;std::weak_ptr作为弱引用不增计数,解决shared_ptr循环引用问题,常用于观察者或缓存。三者结合可安全高效管理堆资源。

C++中,智能指针是管理动态资源(主要是堆内存)的强大工具,它们通过RAII(资源获取即初始化)原则,自动化了内存的生命周期管理,从而有效避免了内存泄漏、野指针和重复释放等常见问题。在我看来,它们是现代C++编程中不可或缺的基石,极大提升了代码的健壮性和可维护性。
要有效管理C++中的动态资源,核心在于使用标准库提供的三种智能指针:
std::unique_ptr
std::shared_ptr
std::weak_ptr
unique_ptr
shared_ptr
weak_ptr
shared_ptr
std::unique_ptr
std::unique_ptr
unique_ptr
unique_ptr
它的一个显著特点是不可复制,只能通过
std::move
unique_ptr
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <memory>
#include <string>
class MyResource {
public:
MyResource(const std::string& name) : name_(name) {
std::cout << "MyResource " << name_ << " created." << std::endl;
}
~MyResource() {
std::cout << "MyResource " << name_ << " destroyed." << std::endl;
}
void doSomething() {
std::cout << "MyResource " << name_ << " is doing something." << std::endl;
}
private:
std::string name_;
};
// 函数返回一个unique_ptr,所有权转移给调用方
std::unique_ptr<MyResource> createResource(const std::string& name) {
return std::make_unique<MyResource>(name); // 推荐使用make_unique
}
int main() {
std::cout << "--- unique_ptr example ---" << std::endl;
std::unique_ptr<MyResource> res1 = createResource("A");
res1->doSomething();
// 尝试复制会编译错误:std::unique_ptr<MyResource> res2 = res1;
// 所有权转移
std::unique_ptr<MyResource> res2 = std::move(res1);
if (res1 == nullptr) { // res1现在为空
std::cout << "res1 is now empty after move." << std::endl;
}
res2->doSomething();
// 当res2超出作用域时,MyResource "A" 将被销毁
std::cout << "--- unique_ptr example end ---" << std::endl;
return 0;
}在我看来,
std::make_unique
unique_ptr
new
unique_ptr
std::shared_ptr
聊完了独占的
unique_ptr
std::shared_ptr
shared_ptr
shared_ptr
shared_ptr
这种共享所有权模型非常灵活,尤其在实现一些复杂的数据结构或设计模式时显得尤为重要,比如图结构中的节点、观察者模式中的主题等。我常遇到需要多个模块共同持有某个配置对象或数据缓存的情况,这时候
shared_ptr
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class SharedResource {
public:
SharedResource(const std::string& id) : id_(id) {
std::cout << "SharedResource " << id_ << " created." << std::endl;
}
~SharedResource() {
std::cout << "SharedResource " << id_ << " destroyed." << std::endl;
}
void report() {
std::cout << "SharedResource " << id_ << " is active." << std::endl;
}
private:
std::string id_;
};
int main() {
std::cout << "--- shared_ptr example ---" << std::endl;
std::shared_ptr<SharedResource> s_res1 = std::make_shared<SharedResource>("X");
s_res1->report();
std::cout << "Reference count for X: " << s_res1.use_count() << std::endl;
// 复制shared_ptr,引用计数增加
std::shared_ptr<SharedResource> s_res2 = s_res1;
std::cout << "Reference count for X: " << s_res1.use_count() << std::endl;
// 放入容器中,引用计数再次增加
std::vector<std::shared_ptr<SharedResource>> resources;
resources.push_back(s_res1);
std::cout << "Reference count for X: " << s_res1.use_count() << std::endl;
// s_res2超出作用域,引用计数减少
{
std::shared_ptr<SharedResource> s_res3 = s_res1;
std::cout << "Reference count for X: " << s_res1.use_count() << std::endl;
} // s_res3销毁
std::cout << "Reference count for X: " << s_res1.use_count() << std::endl;
// 当所有shared_ptr实例都销毁后,SharedResource "X" 才会被销毁
std::cout << "--- shared_ptr example end ---" << std::endl;
return 0;
}和
unique_ptr
std::make_shared
shared_ptr
shared_ptr
std::weak_ptr
这玩意儿,
std::weak_ptr
std::shared_ptr
weak_ptr
shared_ptr
什么是循环引用?想象一下,对象A有一个
shared_ptr
shared_ptr
shared_ptr
weak_ptr
lock()
shared_ptr
shared_ptr
lock()
shared_ptr
shared_ptr
#include <iostream>
#include <memory>
#include <string>
class B; // 前向声明
class A {
public:
std::shared_ptr<B> b_ptr;
A() { std::cout << "A created." << std::endl; }
~A() { std::cout << "A destroyed." << std::endl; }
};
class B {
public:
// 使用weak_ptr打破循环引用
std::weak_ptr<A> a_ptr;
B() { std::cout << "B created." << std::endl; }
~B() { std::cout << "B destroyed." << std::endl; }
void checkA() {
if (auto shared_a = a_ptr.lock()) { // 尝试获取shared_ptr
std::cout << "B can access A." << std::endl;
} else {
std::cout << "A has been destroyed." << std::endl;
}
}
};
int main() {
std::cout << "--- weak_ptr breaking circular reference example ---" << std::endl;
std::shared_ptr<A> a = std::make_shared<A>();
std::shared_ptr<B> b = std::make_shared<B>();
// 建立循环引用
a->b_ptr = b;
b->a_ptr = a; // 这里使用weak_ptr
std::cout << "A's ref count: " << a.use_count() << std::endl; // 1 (b_ptr持有B,B的weak_ptr不影响A的计数)
std::cout << "B's ref count: " << b.use_count() << std::endl; // 1 (a_ptr持有A)
b->checkA(); // B可以访问A
// 当a和b超出作用域时,它们将分别被销毁
// 如果B中a_ptr也是shared_ptr,这里不会调用析构函数
std::cout << "--- weak_ptr example end ---" << std::endl;
return 0;
}除了解决循环引用,
weak_ptr
weak_ptr
shared_ptr
总而言之,C++智能指针是现代C++内存管理的核心。
unique_ptr
shared_ptr
weak_ptr
shared_ptr
以上就是C++如何使用智能指针管理动态资源的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号