Reputation: 11
I'm feeling confusion that is there any way to count the reference of an object of the class?
class A
{
public :
A(){}
}
int main()
{
A obj;
A * ptr1 = &obj;
A * ptr2 = &obj;
A * ptr3 = &obj;
}
now how i'll be able to know that my object obj is referenced by three pointers.
Upvotes: 0
Views: 80
Reputation: 8985
Raw pointers do not do reference-counting. You would need to either implement a reference-counting smart pointer class yourself, or use an already existing one, such as std::shared_ptr
.
shared_ptr
allows you to access its reference count with the use_count()
member function.
For example:
#include <memory>
#include <iostream>
class A
{
public :
A(){}
}
int main()
{
//Dynamically allocate an A rather than stack-allocate it, as shared_ptr will
//try to delete its object when the ref count is 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
return 0;
}
Upvotes: 4
Reputation: 25799
Only if you implement it yourself. If you come from a C# or Java (or other managed language) then this can be a difficult concept.
You would be better using one of the standard pointer types provided by C++11 or Boost.
For example, shared_ptr<T>
will keep a count of all the 'references' to your objects and manage the lifecycle. unique_ptr<T>
will only allow a single pointer to your object.
Upvotes: 2