国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

c++智能指針(smart pointer)詳解

2019-11-08 03:15:59
字體:
供稿:網(wǎng)友

Smart Pointer

Deal with c++11’s smart pointer facility.

brief

Smart pointers are class objects that behave like built-in pointers but also manage objects that you create with new so that you don’t have to worry about when and whether to delete them - the smart pointers automatically delete the managed object for you at the apPRopriate time.

shared_ptrweak_ptrunique_ptr

shared_ptr (共享指針)

referenced-counted smart pointerShared Ownership with shared_ptr

引用計(jì)數(shù)智能指針:可以和其他 boost::shared_ptr 類型的智能指針共享所有權(quán)。 在這種情況下,當(dāng)引用對(duì)象的最后一個(gè)智能指針銷毀后或者被重新賦值或者使用了reset(),對(duì)象才會(huì)被釋放。多個(gè)shared_ptr對(duì)象可以擁有同一個(gè)對(duì)象。

在繼承中的例子:

shared_ptr<Thing> base_ptr(new Thing(2)); shared_ptr<Food> derived_ptr; ///if static_cast<Derived* >(base_ptr.get()) is valid, then the following is valid: base_ptr->showID(); ///cast failed derived_ptr = static_pointer_cast<Food>(base_ptr); shared_ptr<Food> a(new Food);// a->showID(); derived_ptr->showID();

使用 make_shared 更加高效

There are actually two dynamic memory allocations that happen: one for the object itself from the new, and then a second for the manager object created by the shared_ptr constructor. Since memory allocations are slow, this means that creating a shared_ptr is slow relative to using either a raw pointer, or a so-called “intrusive” reference- counted smart pointer where the reference count is a member variable of the object. To address this problem, C++11 includes a function template make_shared that does a single memory allocation big enough to hold both the manager object and the new object, passing along any constructor parameters that you specify, and returns a shared_ptr of the specified type, which can then be used to initialize the shared_ptr that you are creating (with efficient move semantics).

shared_ptr<Thing> p(new Thing); // ouch - two allocations shared_ptr<Thing> p1(make_shared<Thing>()); // only one allocation!

注意

使用 share_ptr copy assignment 或者構(gòu)造函數(shù)會(huì)使shared_ptr的引用計(jì)數(shù)加1使用 reset() 成員函數(shù)可以使當(dāng)前share_ptr為空,刪除指向?qū)ο蟮闹羔樛ㄟ^給share_ptr賦值 nullptr 可以達(dá)到第二條的效果不允許原生指針與智能指針之間的直接賦值轉(zhuǎn)換不要直接從原生指針構(gòu)造兩個(gè)功能相同的smart pointer,否則會(huì)造成double-deletion錯(cuò)誤可以通過 get() 函數(shù)獲得原生指針在繼承關(guān)系或者其他的轉(zhuǎn)換時(shí),可以使用 static_pointer_castdynamic_pointer_castconst_pointer_cast

weak_ptr

Weak pointers just “observe” the managed object; they don’t “keep it alive” or affect its lifetime. Unlike shared_ptrs, when the last weak_ptr goes out of scope or disappears, the pointed-to object can still exist because the weak_ptrs do not affect the lifetime of the object - they have no ownership rights. But the weak_ptr can be used to determine whether the object exists, and to provide a shared_ptr that can be used to refer to it.

僅僅觀察被管理的對(duì)象,對(duì)其生命周期不產(chǎn)生任何影響

1.weak_ptr build-in-pointer might zero.

void do_it(weak_ptr<Thing> wp){shared_ptr<Thing> sp = wp.lock();// get shared_ptr from weak_ptr if(sp) sp->defrangulate(); // tell the Thing to do something else cout << "The Thing is gone!" << endl;}

2.This approach is useful as a way to simply ask whether the pointed-to object still exists.

bool is_it_there(weak_ptr<Thing> wp) { if(wp.expired()) { cout << "The Thing is gone!" << endl; return false; } return true; }

3.if the weak_ptr is expired, an exception is thrown, of type std::bad_weak_ptr.

void do_it(weak_ptr<Thing> wp){shared_ptr<Thing> sp(wp); // construct shared_ptr from weak_ptr // exception thrown if wp is expired, so if here, sp is good to go sp->defrangulate(); // tell the Thing to do something} try { do_it(wpx); } catch(bad_weak_ptr&) { cout << "A Thing (or something else) has disappeared!" << endl; }

4.inherit from enabled_shared_from_this/

否則會(huì)出現(xiàn)的錯(cuò)誤 error:pointer being freed was not allocated

class Thing:public enable_shared_from_this<Thing>{public: int id;public: virtual void showID() const; Thing(); Thing(int _id); void foo();};void Thing::foo() { shared_ptr<Thing> t1 = shared_from_this(); t1->showID();}

公有繼承enable_shared_from_this/ ,則Thing類有了一個(gè)weak_ptr 作為成員變量。當(dāng)?shù)谝粋€(gè)shared_ptr創(chuàng)建時(shí),從第一個(gè)shared_ptr中初始化該weak_ptr/,當(dāng)需要一個(gè)指向this的share_ptr時(shí)調(diào)用shared_from_this()成員函數(shù),返回一個(gè)由weak_prt/構(gòu)造而來的shared_ptr/,使得返回的shared_ptr與第一次的shared_ptr是相同的 manage object.

注意

weak_ptr 與 share_ptr 結(jié)合使用,僅通過從share_ptr的復(fù)制和賦值,或者來源與其他weak_ptr。lock() 函數(shù)檢查weak_ptr指向的對(duì)象是否存在,如果不存在返回一個(gè)空的share_ptr,否則返回一個(gè)指向該對(duì)象的share_ptr.不能使用給weak_ptr賦值nullptr的方式,只能通過reset()方法expired()函數(shù)返回weak_ptr是否為存在非空對(duì)象。在構(gòu)造函數(shù)中不可以使用shared_from_this盡可能多的搭配使用share_ptr和weak_ptr,自動(dòng)化內(nèi)存管理。

unique_ptr

With a unique_ptr, you can point to an allocated object, and when the unique_ptr goes out of scope, the pointed-to object gets deleted, and this happens regardless of how we leave the function, either by a return or an exception being thrown somewhere.

unique_ptr implements a unique ownership concept - an object can be owned by only one unique_ptr at a time - the opposite of shared ownership.

unique_ptr 隱式的刪除了copy構(gòu)造函數(shù),和copy assignment操作符,不允許一個(gè)對(duì)象同時(shí)被多個(gè)unique_ptr擁有這恰恰與shared_ptr相反。

The unique ownership is enforced by disallowing (with =delete) copy construction and copy assignment.So unlike built-in pointers or shared_ptr, you can’t copy or assign a unique_ptr to another unique_ptr.

move semantics: the move constructor and move assignment Operator are defined for unique_ptr so that they transfer ownership from the original owner to the new owner.

可以通過move構(gòu)造函數(shù)和move assignment 操作符使得unique_ptr的所屬權(quán)從原來的轉(zhuǎn)移到新的。轉(zhuǎn)移之后原來的unique_ptr不包含任何對(duì)象。

隱式的從右值轉(zhuǎn)換

unique_ptr<Thing> create_Thing() { unique_ptr<Thing> local_ptr(new Thing); return local_ptr; // local_ptr will surrender ownership }void foo() { unique_ptr<Thing> p1(create_Thing()); // move ctor from returned rvalue // p1 now owns the Thing unique_ptr<Thing> p2; // default ctor'd; owns nothing p2 = create_Thing(); // move assignment from returned rvalue // p2 now owns the second Thing}

顯式的使用move assignment 和 move construction進(jìn)行轉(zhuǎn)換

unique_ptr<Thing> p1(new Thing); // p1 owns the Thingunique_ptr<Thing> p2; // p2 owns nothing// invoke move assignment explicitlyp2 = std::move(p1); // now p2 owns it, p1 owns nothing// invoke move construction explicitlyunique_ptr<Thing> p3(std::move(p2)); // now p3 owns it, p2 and p1 own nothing

注意

通過reset()函數(shù)或者給unique_ptr賦值nullptr,可以手工的刪除對(duì)象。

reference

c++11 smart pointer


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 衡东县| 舞钢市| 桐庐县| 望城县| 中牟县| 长泰县| 佛学| 丁青县| 图们市| 钟山县| 琼海市| 宜城市| 来宾市| 扶余县| 中超| 凤山县| 奉贤区| 通榆县| 青岛市| 沙田区| 那坡县| 额济纳旗| 都匀市| 沁源县| 泗洪县| 新泰市| 措美县| 凤凰县| 团风县| 鹿邑县| 南安市| 黄浦区| 普定县| 牙克石市| 枞阳县| 长寿区| 长寿区| 阳谷县| 阿坝县| 阿坝县| 东阳市|