Should Local Variable Initialisation Be Mandatory?

前端 未结 17 2444
忘掉有多难
忘掉有多难 2021-02-14 01:26

The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still se

17条回答
  •  滥情空心
    2021-02-14 02:01

    Just a secondary observation. Initializations are only EASILY optimized on primitive types or when assigned by const functions.

    a= foo();

    a= foo2();

    Cannot be easily optimized because foo may have side effects.

    Also heap allocations before time might result in huge performance hits. Take a code like

    void foo(int x)
    

    {

    ClassA *instance= new ClassA();

    //... do something not "instance" related... if(x>5) {

    delete instance;
    
    return;
    

    }

    //.. do something that uses instance

    }

    On that case, simply declare instance just when you will use it, and initialize it only there. And no The compiler Cannot optimize that for you since the constructor may have side effects that code reordering would change.

    edit: I fail at using the code listing feature :P

提交回复
热议问题