C++ - Dynamic memory allocation required memory
If I want to allocate memory dynamically to an int
object, I can do this:
int *x = new int;
In this case, I know that the heap reseves 开发者_如何学C4-bytes
of memory for an int
object.
But, if I have a user-defined
class (type) and wanted to allocate memory dynamically, as follows:
Car *c = new Car;
How can I know the required amount of memory to be reserved on the heap for a Car
object?
Thanks.
That will be the sizeof(Car)
bytes. Compiler will do this automatically, you need not do anything specific.
See this article for information about how the size of a class object is determined. It's available to you programatically using:
size_t car_size = sizeof(Car);
You're looking for sizeof()
. Note that this value may be larger than expected for user-defined types due to memory padding and/or alignment.
You want to use the sizeof
operator. The sizeof operator returns the size of your type in bytes, and is evaluated at compile time. This is particularly useful for malloc
since malloc requires you to specify how many bytes you need to allocate. However, you are using C++ and new
does this automatically for you.
The sizeof
operator returns the type size_t
which is found in cstddef
or stddef.h
Example code:
size_t size_in_bytes = sizeof(Car);
精彩评论