State of “memset” functionality in C++ with modern compilers

前端 未结 12 2122
我寻月下人不归
我寻月下人不归 2021-02-12 16:03

Context:

A while ago, I stumbled upon this 2001 DDJ article by Alexandrescu: http://www.ddj.com/cpp/184403799

It\'s about comparing various ways to initialize

12条回答
  •  情书的邮戳
    2021-02-12 16:08

    If you have to allocate your memory as well as initialize it, I would:

    • Use calloc instead of malloc
    • Change as much of my default values to be zero as possible (ex: let my default enumeration value be zero; or if a boolean variable's default value is 'true', store it's inverse value in the structure)

    The reason for this is that calloc zero-initializes memory for you. While this will involve the overhead for zeroing memory, most compilers are likely to have this routine highly-optimized -- more optimized that malloc/new with a call to memcpy.

提交回复
热议问题