C++ Essay
程式開發塗鴉牆
Skip to content
  • 首頁
  • 關於
← wait on thread creation
object slicing →

std::make_shared

Posted on July 18, 2017 by Enrico
//C++11中的 shared_ptr初始化一般使用
std::shared_ptr p(new A);
//但也可以
std::shared_ptr p = std::make_shared();

使用make_shared可以避免顯式地使用new,另外主要的差別在make_shared 一般會將shared_ptr內的control block和object一起allocate。雖然一次allocate上比較有效率,但如果有用到weak_ptr,當shared count = 0時,不會馬上還回記憶體,因為control block還需要用到,而是要等到沒有任何shared_ptr, weak_ptr參考時,才會釋放記憶體。

在N3690文件 20.9.2.2.6 shared_ptr creation 中提到:

Remarks: Implementations should perform no more than one memory allocation. [ Note: This provides efficiency equivalent to an intrusive smart pointer. — end note ]
[ Note: These functions will typically allocate more memory than sizeof(T) to allow for internal bookkeeping structures such as the reference counts. — end note ]

參考:
https://isocpp.org/files/papers/N3690.pdf
http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared

This entry was posted in C++ Language. Bookmark the permalink.
← wait on thread creation
object slicing →

Leave a Reply Cancel reply

You must be logged in to post a comment.

  • May 2025
    S M T W T F S
    « Jan    
     123
    45678910
    11121314151617
    18192021222324
    25262728293031
  • Recent Posts

    • One Definition Rule – class type
    • json-rpc整理(JSON remote procedure call)
    • xml-rpc整理 (XML remote procedure call) – spec
    • xml-rpc整理 (XML remote procedure call) – introduction
    • longest palindromic substring 演算法整理 (Manacher’s algorithm)
  • Recent Comments

    • WebSocket node.js ws source 整理 – 1 | C++ Essay on Nodejs Events 整理
    • WebSocket node.js ws source 整理 – 1 | C++ Essay on WebSocket protocol整理
    • Nodejs Events 整理 | C++ Essay on Node.js event .once 使用時機
  • Categories

    • Algorithm
    • Brainstorming
    • C Language
    • C++ idioms
    • C++ Language
    • Distributed
    • Front-end
    • General
    • Library
    • MOM
    • Network
    • nodejs
    • System Administration
    • Tips
  • Links

    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.org
C++ Essay
©️2017-2020 cppext.com