Members of a struct/class are stored in the memory block that is allocated for an object instance of that struct/class (whether that be on the stack or the heap does not matter, but is dependent on how the object is allocated). The size of an object in memory is the total size of its data members, plus any padding the compiler adds between them for alignment purposes.
new type
allocates a block of dynamic memory that is at least sizeof(type)
bytes in size (it may be more for memory manager overhead) and then calls the type's constructor on that memory block.
So, for example, if you have this class:
class Engine
{
private:
int numOfThings;
...
};
Then any instance of that class takes up sizeof(Engine)
bytes of memory, where the first 4 bytes are occupied by the numOfThings
member. That could be automatic memory:
Engine engine;
Or it could be dynamic memory:
Engine *engine = new Engine;
Now, lets say that Engine
has other members that are either automatic or dynamic, eg:
class Engine
{
private:
int numOfThings;
uint32_t values[16];
std::string name;
uint8_t *data;
Engine()
{
data = new uint8_t[256];
}
~Engine()
{
delete[] data;
}
};
The value
member is (sizeof(uint32_t) * 16)
(4*16=64) bytes in size, which is added to the total size of the Engine
class.
The name
member is sizeof(std::string)
bytes in size (which varies depending on STL implementation), which is added to the total size of the Engine
class. However, internally std::string
has a pointer to dynamic memory it allocates for character data. The size of that memory is not included in the total size of the Engine
class.
The data
pointer is sizeof(uint8_t*)
bytes in size (4 on 32bit systems, 8 on 64bit systems), which is added to the total size of the Engine
class. The memory block that data
points at is (sizeof(uint8_t) * 256)
(1*256=256) bytes in size, and is stored elsewhere in dynamic memory.
Variables that are declared local inside of a class method are not part of the class itself, and thus do not count towards its size. Only data members that are declared in the class definition are counted towards its size.