C++ Using the new operator efficiently

前端 未结 3 1185
时光取名叫无心
时光取名叫无心 2021-01-14 09:04

When instantiating a class with new. Instead of deleting the memory what kinds of benefits would we gain based on the reuse of the objects?

What is the process of n

3条回答
  •  离开以前
    2021-01-14 09:36

    • new allocates memory for the class on the heap, and calls the constructor.
    • context switches do not have to occur.
    • The c++-runtime allocates the memory on its freestore using whatever mechanism it deems fit.

    Usually the c++ runtime allocates large blocks of memory using OS memory management functions, and then subdivides those up using its own heap implementation. The microsoft c++ runtime mostly uses the Win32 heap functions which are implemented in usermode, and divide up OS memory allocated using the virtual memory apis. There are thus no context switches until and unless its current allocation of virtual memory is needed and it needs to go to the OS to allocate more.

    There is a theoretical problem when allocating memory that there is no upper bound on how long a heap traversal might take to find a free block. Practically tho, heap allocations are usually fast.

    With the exception of threaded applications. Because most c++ runtimes share a single heap between multiple threads, access to the heap needs to be serialized. This can severly degrade the performance of certain classes of applications that rely on multiple threads being able to new and delete many objects.

提交回复
热议问题