c++智慧指標的使用,shared_ptr,unique_ptr,weak_ptr
c++智慧指標的使用
普通指標的煩惱:記憶體洩漏,多次釋放,提前釋放
智慧指標 負責自動釋放所指向的物件。
三種智慧指標 shared_ptr,unique_ptr,weak_ptr;
將shared_ptr存放在一個容器中,不再需要它的時候,要erase掉。
allocator負責封裝堆記憶體管理的物件,它們在整個標準庫中使用,特別是STL容器使用它們來管理容器內部的所有記憶體分配,大部份情況下,程式設計師不用理會,標準容器使用預設的分配器稱為std :: allocator。
shared_ptr
shared_ptr
多個指標指向相同的物件;
使用引用計數,引用計數是執行緒安全的,但是物件的讀寫需要加鎖。
不可以直接將指標直接賦值給一個智慧指標,因為指標指標是一個類。
get獲取原始指標
最大的陷阱就是迴圈引用,這會導致記憶體無法正確釋放,導致記憶體洩漏
#include <iostream> #include <memory> #include <thread> #include <chrono> #include <mutex> struct Base { Base() { std::cout << " Base::Base()\n"; } // 注意:此處非虛解構函式 OK ~Base() { std::cout << " Base::~Base()\n"; } }; struct Derived: public Base { Derived() { std::cout << " Derived::Derived()\n"; } ~Derived() { std::cout << " Derived::~Derived()\n"; } }; void thr(std::shared_ptr<Base> p) { std::this_thread::sleep_for(std::chrono::seconds(1)); std::shared_ptr<Base> lp = p; // 執行緒安全,雖然自增共享的 use_count { static std::mutex io_mutex; std::lock_guard<std::mutex> lk(io_mutex); std::cout << "local pointer in a thread:\n" << " lp.get() = " << lp.get() << ", lp.use_count() = " << lp.use_count() << '\n'; } } int main() { std::shared_ptr<Base> p = std::make_shared<Derived>(); std::cout << "Created a shared Derived (as a pointer to Base)\n" << " p.get() = " << p.get() << ", p.use_count() = " << p.use_count() << '\n'; std::thread t1(thr, p), t2(thr, p), t3(thr, p); p.reset(); // 從 main 釋放所有權 std::cout << "Shared ownership between 3 threads and released\n" << "ownership from main:\n" << " p.get() = " << p.get() << ", p.use_count() = " << p.use_count() << '\n'; t1.join(); t2.join(); t3.join(); std::cout << "All threads completed, the last one deleted Derived\n"; }
可能的輸出:
Base::Base() Derived::Derived() Created a shared Derived (as a pointer to Base) p.get() = 0x2299b30, p.use_count() = 1 Shared ownership between 3 threads and released ownership from main: p.get() = 0, p.use_count() = 0 local pointer in a thread: lp.get() = 0x2299b30, lp.use_count() = 5 local pointer in a thread: lp.get() = 0x2299b30, lp.use_count() = 3 local pointer in a thread: lp.get() = 0x2299b30, lp.use_count() = 2 Derived::~Derived() Base::~Base() All threads completed, the last one deleted Derived
weak_ptr
是為了配合shared_ptr而引入的一種智慧指標,沒有過載operator*和->,它的最大作用在於協助shared_ptr工作,像旁觀者那樣觀測資源的使用情況。
weak_ptr可以從一個shared_ptr或者另一個weak_ptr物件構造,獲得資源的觀測權。但weak_ptr沒有共享資源,它的構造不會引起指標引用計數的增加。
成員函式expired()的功能等價於use_count()==0,
weak_ptr可以使用一個非常重要的成員函式lock()從被觀測的shared_ptr獲得一個可用的shared_ptr物件
#include <iostream>
#include <memory>
std::weak_ptr<int> gw;
void observe()
{
std::cout << "use_count == " << gw.use_count() << ": ";
if (auto spt = gw.lock()) { // 使用之前必須複製到 shared_ptr
std::cout << *spt << "\n";
}
else {
std::cout << "gw is expired\n";
}
}
int main()
{
{
auto sp = std::make_shared<int>(42);
gw = sp;
observe();
}
observe();
}
輸出:
use_count == 1: 42
use_count == 0: gw is expired
unique_ptr
unique_ptr
唯一擁有物件
通過reset方法重新指定
通過release方法釋放所有權
#include <iostream>
#include <vector>
#include <memory>
#include <cstdio>
#include <fstream>
#include <cassert>
#include <functional>
struct B {
virtual void bar() { std::cout << "B::bar\n"; }
virtual ~B() = default;//父類的解構函式需要定義為虛擬函式,防止記憶體洩漏
};
struct D : B
{
D() { std::cout << "D::D\n"; }
~D() { std::cout << "D::~D\n"; }
void bar() override { std::cout << "D::bar\n"; }
};
// 消費 unique_ptr 的函式能以值或以右值引用接收它
std::unique_ptr<D> pass_through(std::unique_ptr<D> p)
{
p->bar();
return p;
}
void close_file(std::FILE* fp) { std::fclose(fp); }
int main()
{
std::cout << "unique ownership semantics demo\n";
{
auto p = std::make_unique<D>(); // p 是佔有 D 的 unique_ptr
auto q = pass_through(std::move(p));
assert(!p); // 現在 p 不佔有任何內容並保有空指標
q->bar(); // 而 q 佔有 D 物件
} // ~D 調用於此
std::cout << "Runtime polymorphism demo\n";
{
std::unique_ptr<B> p = std::make_unique<D>(); // p 是佔有 D 的 unique_ptr
// 作為指向基類的指標
p->bar(); // 虛派發
std::vector<std::unique_ptr<B>> v; // unique_ptr 能儲存於容器
v.push_back(std::make_unique<D>());
v.push_back(std::move(p));
v.emplace_back(new D);
for(auto& p: v) p->bar(); // 虛派發
} // ~D called 3 times
std::cout << "Custom deleter demo\n";
std::ofstream("demo.txt") << 'x'; // 準備要讀的檔案
{
std::unique_ptr<std::FILE, void (*)(std::FILE*) > fp(std::fopen("demo.txt", "r"),
close_file);
if(fp) // fopen 可以開啟失敗;該情況下 fp 保有空指標
std::cout << (char)std::fgetc(fp.get()) << '\n';
} // fclose() 調用於此,但僅若 FILE* 不是空指標
// (即 fopen 成功)
std::cout << "Custom lambda-expression deleter demo\n";
{
std::unique_ptr<D, std::function<void(D*)>> p(new D, [](D* ptr)
{
std::cout << "destroying from a custom deleter...\n";
delete ptr;
}); // p 佔有 D
p->bar();
} // 呼叫上述 lambda 並銷燬 D
std::cout << "Array form of unique_ptr demo\n";
{
std::unique_ptr<D[]> p{new D[3]};
} // 呼叫 ~D 3 次
}
輸出:
unique ownership semantics demo
D::D
D::bar
D::bar
D::~D
Runtime polymorphism demo
D::D
D::bar
D::D
D::D
D::bar
D::bar
D::bar
D::~D
D::~D
D::~D
Custom deleter demo
x
Custom lambda-expression deleter demo
D::D
D::bar
destroying from a custom deleter...
D::~D
Array form of unique_ptr demo
D::D
D::D
D::D
D::~D
D::~D
D::~D
shared_ptr迴圈引用的記憶體洩漏問題
如下物件建模——家長與子女:a Parent has a Child, a Child knowshis/her Parent。
從程式的執行中可以看到最終資源沒有得到釋放。
一個智慧指標在建立一個物件的時候初始化引用計數為 1,並把自己的指標指向建立的物件。但這個引用計數在何處?在智慧指標內部?非也,這個計數是一個單獨的物件來實現的,如圖1,當另外一個智慧指標指向這個物件的時候,便找到與這個物件對應的計數物件,並加一個引用,即 use_count++。這樣多個智慧指標物件便可以使用相同的引用計數。
下面程式中,當指標p釋放時,由於指標c->ParentPtr還在引用著new Child,所以這時(new Child)的use_count從2減為1。同理當指標c釋放時,由於p->ChildPtr還在引用著new Parent,所以這時(new Parent)的use_count從2減為1。最終,記憶體沒有被釋放完全。
class Child;
class Parent;
class Parent {
private:
std::shared_ptr<Child> ChildPtr;
public:
void setChild(std::shared_ptr<Child> child) {
this->ChildPtr = child;
}
void doSomething() {
if (this->ChildPtr.use_count()) {
}
}
~Parent() {}
};
class Child {
private:
std::shared_ptr<Parent> ParentPtr;
public:
void setPartent(std::shared_ptr<Parent> parent) {
this->ParentPtr = parent;
}
void doSomething() {
if (this->ParentPtr.use_count()) {
}
}
~Child() {}
};
int main() {
std::weak_ptr<Parent> wpp;
std::weak_ptr<Child> wpc;
{
std::shared_ptr<Parent> p(new Parent);
std::shared_ptr<Child> c(new Child);
std::cout << "p.use_count() = " << p.use_count() << std::endl;
std::cout << "c.use_count() = " << c.use_count() << std::endl;
p->setChild(c);
c->setPartent(p);
std::cout << "p.use_count() = " << p.use_count() << std::endl;
std::cout << "c.use_count() = " << c.use_count() << std::endl;
wpp = p;
wpc = c;
std::cout << "p.use_count() = " << p.use_count() << std::endl; // 2
std::cout << "c.use_count() = " << c.use_count() << std::endl; // 2
cout<<endl;
}
std::cout << "p.use_count() = " << wpp.use_count() << std::endl; // 1
std::cout << "c.use_count() = " << wpc.use_count() << std::endl; // 1
return 0;
}
執行結果
p.use_count() = 1
c.use_count() = 1
p.use_count() = 2
c.use_count() = 2
p.use_count() = 2
c.use_count() = 2
p.use_count() = 1
c.use_count() = 1
shared_ptr迴圈引用的記憶體洩漏問題解決
如下,在兩個需要互相引用的類的內部,使用weak_ptr智慧指標引用對方,來避免迴圈引用導致的記憶體洩漏問題。
#include <iostream>
#include <memory>
class Child;
class Parent;
class Parent {
private:
//std::shared_ptr<Child> ChildPtr;
std::weak_ptr<Child> ChildPtr;
public:
void setChild(std::shared_ptr<Child> child) {
this->ChildPtr = child;
}
void doSomething() {
//new shared_ptr
if (this->ChildPtr.lock()) {
}
}
~Parent() {
}
};
class Child {
private:
std::shared_ptr<Parent> ParentPtr;
public:
void setPartent(std::shared_ptr<Parent> parent) {
this->ParentPtr = parent;
}
void doSomething() {
if (this->ParentPtr.use_count()) {
}
}
~Child() {
}
};
int main() {
std::weak_ptr<Parent> wpp;
std::weak_ptr<Child> wpc;
{
std::shared_ptr<Parent> p(new Parent);
std::shared_ptr<Child> c(new Child);
p->setChild(c);
c->setPartent(p);
wpp = p;
wpc = c;
std::cout << p.use_count() << std::endl; // 2
std::cout << c.use_count() << std::endl; // 1
}
std::cout << wpp.use_count() << std::endl; // 0
std::cout << wpc.use_count() << std::endl; // 0
return 0;
}
執行結果
2100
更多程式設計資料詳見公眾號 xutopia77