reference count of an object

Hi,
I have a question regarding reference count of an object. How i'll be able to know that how many pointers are pointing to my object.....
If you are talking about raw pointers, there is no way to know that. You cnad use standard library faculties, like shared_ptr, which provides use_count() method
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.
As I said, there is no way. It is technically impossible to make reference counting using raw pointers.

That is one of the reasons why you should not use raw pointers.
You can use std::shared_ptr:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <memory>

struct A {};

int main()
{
    auto ptr1 = std::make_shared<A>();
    auto ptr2(ptr1);
    auto ptr3(ptr1);
    std::cout << ptr2.use_count();
}
3
Topic archived. No new replies allowed.