Does allocating memory and then releasing constitute a side effect in a C++ program?

后端 未结 5 1940
说谎
说谎 2020-12-19 00:52

Inspired by this question about whether the compiler can optimize away a call to a function without side effects. Suppose I have the following code:

delete[]         


        
5条回答
  •  别那么骄傲
    2020-12-19 01:20

    No. Neither should it be removed by compiler nor considered to be a side effect. Consider below:

    struct A {
      static int counter;
      A () { counter ++; }
    };
    
    int main ()
    {
      A obj[2]; // counter = 2
      delete [] new A[3]; // counter = 2 + 3 = 5
    }
    

    Now, if the compiler removes this as side effect then, the logic goes wrong. So, even if you are not doing anything, compiler will always assume that something useful is happening (in constructor). That's the reason why;

    A(); // simple object allocation and deallocation
    

    is not optimized away.

提交回复
热议问题