If you want to track the space used by objects on the stack, you better add tracking to the constructor and destructor. Something like this should do the job. Only potential problem is that there may be dynamically allocated elements that you need to track too.
class Tracked { static int space_used; static int space_released; Tracked() { space_used += sizeof(Tracked); } ~Tracked() { space_released += sizeof(Tracked); } }; int Tracked::space_used = 0; int Tracked::space_released = 0; int main() { { Tracked t; Tracked * t_ptr = new Tracked(); } std::cout<<"used :"<< Tracked::space_used <<std::endl; std::cout<<"released :"<< Tracked::space_released <<std::endl; std::cout<<"live :"<< Tracked::space_used - Tracked::space_released <<std::endl; }
source share