私がカスタムデストラクタを定義している場合、すべての変数を手動で削除する必要がありますか?C++デストラクタの作成
malloc
によって割り当てられたメモリは、デストラクタでfree
になるはずです。 malloc
とint
によって割り当てられたメモリへのポインタはどうですか?
a.h:
#ifndef A_H
#define A_H
#include <stdlib.h>
#include <iostream>
#include <stdint.h>
using namespace std;
class A{
public:
uint32_t x;
uint32_t* ar_y;
A(void);
~A(void);
};
#endif
a.cpp:
#include "a.h"
A::A(void){
x = 0;
ar_y = (uint32_t*)(malloc(4));
}
A::~A(void){
// free the memory allocated by malloc
free(ar_y);
//Is it ok to do nothing for int* y and int x?
}
ます。test.cpp:
#include "a.h"
int f(void){
A objA;
//cout << objA.x << endl;
//Upon exiting the function
//destructor of A is called.
}
int main(void){
uint32_t i;
// see if memory usage go crazy.
for (i = 0; i < 10000000000; i++) f();
}
テスト結果:
メモリ使用量が夢中になって上昇しませんでした。
delete [] yは割り当てられたメモリを解放します。 –
@Bafforastaは、新しいものが使用されていましたが、それは確かに適切です。 – WhozCraig
@WhozCraig私はちょうど彼がなぜしなかったのかさまよっていた –