Determine the size of memory allocated by a new operator in C ++

How to determine the size of memory allocated by the C ++ new. Operator?

In C, malloc has the syntax:

void *malloc(size_t size);

here we know what size we allocate.

but in C ++ we can determine what size is allocated when allocating memory, as shown below. I am interested to know how it newdetermines the size to be allocated.

foo *pFoo = new foo();
+4
source share
3 answers

The C ++ operator newallocates bytes sizeof(T)(using a standard global allocator ::operator new(size_t)or a custom allocator for T, if one has been defined).

( -, T).

, .

+5

new, , :

void* operator new(size_t size)
{
    std::cout << "allocating " << size << std::endl;
    return malloc(size);
}

[ , - .].

+2
void *malloc(size_t size);

, , , , - void *, .

foo *pFoo = new foo();

Here, the size is determined by the new one, looking at the layout of the object. Also note that the new statement calls the foo constructor. If you need it, then you did it for malloc, do it as shown below:

 void * ptr = new size_t[size];

Not even satisfied ..! You can overload the new statement as you want. Google to overload the new operator.

-2
source

Source: https://habr.com/ru/post/1536383/


All Articles