在Linux C++中,智能指针是一种用于自动管理动态分配内存的工具,它们可以帮助开发者避免内存泄漏、野指针等问题。C++11标准引入了三种主要的智能指针:std::unique_ptr
、std::shared_ptr
和std::weak_ptr
。以下是这些智能指针的使用指南:
std::unique_ptr
是一个独占所有权的智能指针,它保证在其生命周期结束时释放所管理的资源。std::unique_ptr
不能被复制,但可以通过移动语义转移所有权。
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructor
"; }
~MyClass() { std::cout << "MyClass destructor
"; }
void doSomething() { std::cout << "Doing something
"; }
};
int main() {
// 使用 std::unique_ptr
std::unique_ptr<MyClass> ptr(new MyClass());
ptr->doSomething();
// 当 ptr 离开作用域时,MyClass 的实例会被自动删除
return 0;
}
std::shared_ptr
允许多个指针共享同一个对象的所有权。它通过引用计数机制来管理对象的生命周期,当最后一个std::shared_ptr
被销毁或重置时,对象才会被删除。
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructor
"; }
~MyClass() { std::cout << "MyClass destructor
"; }
void doSomething() { std::cout << "Doing something
"; }
};
int main() {
// 使用 std::shared_ptr
std::shared_ptr<MyClass> ptr = std::make_shared<MyClass>();
ptr->doSomething();
return 0;
}
std::weak_ptr
是为了配合std::shared_ptr
而引入的一种智能指针,它用于观察但不拥有资源,不会影响对象的生命周期。std::weak_ptr
通常用于解决循环引用问题。
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructor
"; }
~MyClass() { std::cout << "MyClass destructor
"; }
void doSomething() { std::cout << "Doing something
"; }
};
int main() {
std::shared_ptr<MyClass> sharedResource = std::make_shared<MyClass>();
std::weak_ptr<MyClass> weakResource(sharedResource);
if (auto locked = weakResource.lock()) {
// 可以安全访问对象
std::cout << "Accessing resource via weak_ptr." << std::endl;
} else {
std::cout << "Resource has been destroyed." << std::endl;
}
sharedResource.reset(); // 重置 shared_ptr,此时 Resource 被销毁
// 尝试再次锁定 weak_ptr
if (auto lockedAgain = weakResource.lock()) {
std::cout << "Accessing resource via weak_ptr." << std::endl;
} else {
std::cout << "Resource has been destroyed." << std::endl;
}
return 0;
}
在使用智能指针时,需要注意以下几点:
以上就是在Linux C++中使用智能指针的基本指南,希望对你有所帮助。