C++ error: “taking address of temporary array”

后端 未结 6 1897
渐次进展
渐次进展 2021-01-01 04:42

I am trying to declare an array inside an if-statement. I wrote my code this way so that the object stays in scope once the if-block exits, but now I have a new issue: \"tak

6条回答
  •  难免孤独
    2021-01-01 05:26

    (int[9]) {0,1,0,1,-4,1,0,1,0} creates a temporary array which will be destroyed as soon as the full statement is completed. (Note, this is technically not C++, but a C99 feature which your compiler is supporting as an extension in C++.)

    maskArray = (int[9]) {0,1,0,1,-4,1,0,1,0}; takes that temporary array, converts it to a pointer and stores that pointer in maskArray. As soon as this statement completes, the temporary array will be destroyed and the value in maskArray will no longer be valid.

    The only way it's acceptable to use such a temporary array is to use it in that very same statement, such as by passing it to a function which will use it:

    void foo(int (&arr)[9]);
    
    foo((int[9]) {0,1,0,1,-4,1,0,1,0});
    

    This is okay because even though the temporary array is destroyed, it's only destroyed after the function returns and nothing is using the array. (And the function had better not somehow store long-lived references or pointers into the array, but then that's no different from normal.)

提交回复
热议问题