• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 122
  • Last Modified:

22. How much memory requires class object? How to determine that?

How much memory requires class object? How to determine that?
0
Nusrat Nuriyev
Asked:
Nusrat Nuriyev
  • 2
3 Solutions
 
jkrCommented:
The net size of a class can be obtained using 'sizeof()', just like in C, e.g.

#include <iostream>

class Vehicle {
public:
  void Drive() {speed = 42;}
protected:
  int speed;
};

int main() {

  std::cout << "Sizeo of Vehicle is " << sizeof(Vehicle) << std::endl;
  return 0;
}

Open in new window


But, there's a caveat: When a class contains pointer members whose values are allocated dynamically, that memory isn't taken into account by 'sizeof()' - you would have to provide a member that does account for that memory and reports it.
The same applies to classes that use lists or other containers.
0
 
phoffricCommented:
sizeof gives you the macroscopic answer. To optimize your performance you may wish to take a finer look at the reasons your sizeof result may be higher than desired. You may wish to look closer at the cache alignment and data holes in the class data members. To do this use the Linux pahole utility:
http://linux.die.net/man/1/pahole

The goal is to rearrange your data members to minimize the cache lines, to try to keep data members from requiring two cache lines, and to reduce the number of holes in your data members (i.e., wasted portions of cache lines).
0
 
Nusrat NuriyevAuthor Commented:
Jkr,
The same applies to classes that use lists or other containers.
Did you mean stl containers , iterators?

But, there's a caveat: When a class contains pointer members whose values are allocated dynamically, that memory isn't taken into account by 'sizeof()' - you would have to provide a member that does account for that memory and reports it.

Likewise, usual pointer? it always give's us 4 bytes, right?

Good answer, phoffric!
But still this does not solve the problem of dynamic member data allocation size affected when determining size?
Is it possible to get this info?
0
 
jkrCommented:
>> Did you mean stl containers , iterators?

For example, since these are the most common ones. Or, let's say: std::string

>> Likewise, usual pointer? it always give's us 4 bytes, right?

Yes, exactly. But when you dynamically allocate memory to it, you would have to 'manually' account for that. On the other hand, if you argue that this memory is not 'within' the object... but that is a bit short handed, since teh consumption still persists.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now