
C++智能指针有效管理动态分配内存,避免内存泄漏等问题。Linux下的C++开发通常借助<memory></memory>头文件提供的智能指针类型。
本文介绍三种常用智能指针:
std::unique_ptr: 独占式拥有它指向的对象,确保对象在其生命周期结束后被自动释放。不支持复制,但支持移动语义。#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructor called" << std::endl; }
~MyClass() { std::cout << "MyClass destructor called" << std::endl; }
};
int main() {
std::unique_ptr<MyClass> ptr(new MyClass());
// 使用ptr
// ptr离开作用域时,MyClass对象自动销毁
}std::shared_ptr: 允许多个指针共享同一对象的所有权。当最后一个shared_ptr被销毁或重置时,对象被释放。#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructor called" << std::endl; }
~MyClass() { std::cout << "MyClass destructor called" << std::endl; }
};
int main() {
std::shared_ptr<MyClass> ptr1(new MyClass());
{
std::shared_ptr<MyClass> ptr2 = ptr1;
// ptr1和ptr2共享同一对象
} // ptr2销毁,但MyClass对象不会立即销毁,因为ptr1仍然存在
// ptr1销毁时,MyClass对象才销毁
}std::weak_ptr: 与shared_ptr配合使用,指向由shared_ptr管理的对象,但不增加对象的引用计数。用于解决循环引用问题。#include <iostream>
#include <memory>
class B; // Forward declaration
class A {
public:
std::shared_ptr<B> b_ptr;
~A() { std::cout << "A destructor called" << std::endl; }
};
class B {
public:
std::weak_ptr<A> a_ptr;
~B() { std::cout << "B destructor called" << std::endl; }
};
int main() {
std::shared_ptr<A> a(new A());
std::shared_ptr<B> b(new B());
a->b_ptr = b;
b->a_ptr = a;
// a和b销毁时,A和B对象自动销毁,避免循环引用
}选择智能指针类型需根据实际情况:unique_ptr适合单一所有权场景;shared_ptr适合共享所有权场景;weak_ptr则用于避免shared_ptr带来的循环引用问题。
以上就是Linux下C++如何使用智能指针的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号