how to implement a c++ reference count macro?

Is there any way to add something like "ADD_REFCOUNTER" to a class and then each ctor and dtor of this class will be monitored to ensure no memoty leaks happen?
thanks!
To automagically manage reference counts and life times of individual objects with dynamic storage duration,
use std::shared_ptr<> http://en.cppreference.com/w/cpp/memory/shared_ptr

To manage instance counts of objects of a class, something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
template < typename T > struct instance_counted // base class
{
    instance_counted() noexcept { ++instance_cnt ; }
    ~instance_counted() noexcept { --instance_cnt ; }
    instance_counted( const instance_counted& ) noexcept : instance_counted() {}
    instance_counted( instance_counted&& ) noexcept : instance_counted() {}
    instance_counted& operator= ( const instance_counted& ) noexcept { return *this; }
    instance_counted& operator= ( instance_counted&& ) noexcept { return *this; }

    static int instance_cnt ;
};

template < typename T > int instance_counted<T>::instance_cnt = 0 ;


And then, to make a class instance counted, struct A : instance_counted<A> { /* ... */ };

http://coliru.stacked-crooked.com/a/9f4fc25f7707ab6d
thanks very much! it is really useful
Topic archived. No new replies allowed.