質問

I'm using some dynamically allocated arrays of multiprecision variables (from the mpc-library) and wonder if it is necessary both to clear the variables and to delete the arrays to avoid memory leaks etc? In other words, is all the housekeeping in the snippet below necessary?

using namespace std;
#include <gmp.h>
#include <mpfr.h>
#include <mpc.h>

int main() {

    int i;
    mpc_t *mpcarray;
    mpcarray=new mpc_t[3];
    for(i=0;i<3;i++) mpc_init2(mpcarray[i], 64);

    // Manipulations

    for(i=0;i<3;i++) mpc_clear(mpcarray[i]);
    delete [] mpcarray;

    return 0;
}
役に立ちましたか?

解決

Yes, it is necessary.

The general rule of life applies here:

"You should dispose what you use!"

If you don't it results in a memory leak or much worse an Undefined Behavior if the destructor of mpc_t contains code which produces side effects .

Dynamic memory is an feature which provides you explicit memory management for your program and if you use it(calling new or new []) then it is your responsibility to ensure its proper usage (deallocate it by calling delete or delete [] respectively).

Note that you are much better of to use auto/local variables instead of dynamically pointers.
And if you must, you should use smart pointers instead of raw pointers. They provide you advantages of dynamic memory minus the explicit memory management overhead.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top