在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++中使用智能指針的基本指南,希望對你有所幫助。