看板 C_and_CPP 關於我們 聯絡資訊
最近在學 C++11 smart pointer 發現除了 shared_ptr, weak_ptr,unique_ptr, 還有個 enable_shared_from_this, 但我不知道 enable_shared_from_this 的用途在哪??? 好像主要是為了 shared_from_this class base : public std::enable_shared_from_this<base> {}; shared_ptr<base> a= make_shared<base>(); shared_ptr<base> b=a->shared_from_this(); a中的count 會+1, 但是我不繼承 enable_shared_from_this , 不使用 shared_from_this, 直接 shared_ptr<base> b=a; 也是一樣的 a的 count +1, 不是嗎??? 那 enable_shared_from_this 的用途是???? 另外 如果我 class base 繼承了 enable_shared_from_this, 但是卻 unique_ptr<base> a= make_unique<base>(); 這樣會發生什麼事???? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.132.169.16 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1453795474.A.F3B.html
suhorng: 不一樣的點例如, 在 base 裡面時看不到 a 呀 01/26 16:14
喔喔喔 看懂了 也就是說 如果繼承了 enable_shared_from_this, 在自己的 class 中, 可以用 shared_from_this, 把自己也當成一個 shared_ptr 操作, 如果沒有繼承 enable_shared_from_this , 那在自己的class中, 就只能用 this, 傳統的 ptr操作, 沒辦法用 shared_ptr 操作, 不過我還個問題 假如 class base : public std::enable_shared_from_this<base> { public: shared_ptr<base> GetObject(){ return shared_from_this(); } }; class new1: public base{}; 可以這樣直接繼承嗎???? enable_shared_from_this 的 template 依然是 base 嗎???? GetObject 出來依然是 shared_ptr<base> 不是 new1..... 這應該是 template的問題..... 我該怎麼解決這麼問題..... 另外 我class 都把 建構式 藏在 private, 只 friend 到 factory, 可是現在 factory 裡不能 make_shared...... 因為建構式是 private..... 應該是因為 make_shared 實作在別的地方, friend 影響不到那邊..... 這該怎麼解決 = = 真是頭痛......
LiloHuang: 我想重點在於這個例子 http://goo.gl/UkbKBR 01/26 20:54
firose: 出來是 shared_ptr<base> 但仍然是指向 new1 01/26 21:16
firose: 否則也可以 dynamic_pointer_cast 成 shared_ptr<new1> 01/26 21:19
感謝~ 那個問題解決了, 現在就剩 friend的問題 class A { friend class B; private: A(){}; } class B { shared_ptr<A> pA; B():pA(make_shared<A>()){} // 錯誤 不能用 make_shared 只能用 new A(); }; 不知道這有沒有解 = = 因為 make_shared 建構式是在別的地方做, 那邊不在friend的範圍, 所以 只能用 new, 但是文件說 new的效能比較差, 官方建議用 make_shared 其實有看到一些拐彎抹角的方法 例如在 class B 中, 再宣告 claa A2:public A{} 這樣就可以 make_shared<A2>() 或是在 class A 中, 增加 static shared_ptr<A> make(){ return make_shared<A>(); } 但這兩個我都不喜歡 = =
bibo9901: 我看不懂你把A的實作隱藏後,再於B公開的用意? 01/27 14:11
bibo9901: 是pimpl嗎? 也不太像 01/27 14:12
B 是 A的 factory, 我希望只有 B 可以 new A, 任何其他地方都不可以new A, 我上面寫的 class B 只是範例, 實際上會長的更複雜點, _______________________________ 看了很多篇文章 整合出一個奇怪的方法, class B { private: Key key; B(){ make_shared<A>(key); } }; class Key { friend class B; private: Key(){} }; class A { public: A( Key& _k ){} }; B 是 A 的 factory, 所以只有 B 能 new A, A 改成 public, 但必須有 Key 才能 new A, 而 Key 只有 B 才能有, 所以 只有 B 才能 new A, B 是 單一物件模式, 所以也是 private和 static, 這樣我 friend 也可以少用了, 只有 key 會用到 friend, ※ 編輯: yhn0tgb60 (220.132.169.16), 01/30/2016 00:58:25