why c++ use memset(addr,0,sizeof(T)) to construct a object? Standard or compiler bug?

前端 未结 2 1351
花落未央
花落未央 2021-01-18 23:49

This question is related to another post of mine: why allocate_shared and make_shared so slow

In here I can describe the question more clearly.

Think about t

2条回答
  •  甜味超标
    2021-01-19 00:35

    A a(t...);
    

    Will be parsed as initializing a with t.... When t... is empty, as when you call it, this will be understood as value-initializing a.

    For A without a user-provided default constructor, value-initialize is to zero all its members, hence the memset.

    When you provide a constructor for A, value-initialize is to call the default constructor, which you defined to be do nothing, therefore no memset will be called.

    This is not a bug in the compiler, this is required behaviour. To remove the redundant memset, you could just write A a;. In this case a is default-initialized and no automatic zeroing occurs, with or without the user-provided constructor.

    † This is important since A a() will be parsed as a function called a with return type A

提交回复
热议问题