Smart Pointer c++11
Sep 4, 2018 · 1 min read
最近一直被問到smart pointer 簡單的看了一下,
分成3種
unique_ptr, shared_ptr, weak_ptr
weak_ptr 先想成是一般 pointer, compiler不幫忙check
shared_ptr是會做garbage collection 的pointer,
shared_ptr與weak_ptr是可以pointer to the same addr的
shared_ptr compiler會建立strong reference ref++
當ref變成0時就被gc delete掉
weak_ptr可以指向shared_ptr但不影響reference count 因此可能point to null
unique_ptr 是mutual存在的 意指不會出現同時2個unique_ptr point to the same addr.
compiler check的方式是使用move 然後把前一手的unique_ptr清掉
unique_ptr<int> p = new int(1);
unique_<int> q = move(p) ==> after this p is invalid ownership is moved to q