//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