c++ - counting of references of an object -
c++ - counting of references of an object -
i'm feeling confusion there way count reference of object of class?
class { public : a(){} } int main() { obj; * ptr1 = &obj; * ptr2 = &obj; * ptr3 = &obj; }
now how i'll able know object obj referenced 3 pointers.
raw pointers not reference-counting. need either implement reference-counting smart pointer class yourself, or utilize existing one, such std::shared_ptr
.
shared_ptr
allows access reference count use_count()
fellow member function.
for example:
#include <memory> #include <iostream> class { public : a(){} } int main() { //dynamically allocate rather stack-allocate it, shared_ptr //try delete object when ref count 0. std::shared_ptr<a> ptr1(new a()); std::shared_ptr<a> ptr2(ptr1); std::shared_ptr<a> ptr3(ptr1); std::cout<<"count: "<<ptr1.use_count()<<std::endl; //count: 3 homecoming 0; }
c++
Comments
Post a Comment