C++構造関数と解析関数の詳細(二)---自由記憶newとdelete

1148 ワード

フリーストレージでオブジェクトを作成すると、delete関数がポインタに作用するまで、関連するコンストラクション関数がnewによって呼び出されます.
サンプルコード:
#include<iostream>
using namespace std;

class Test
{
public:
	Test(){cout << "        "<<endl;};
	~Test(){cout << "      ~" <<endl;}
};

int main()
{
	Test* p  =new Test;
	Test* q = new Test;
	delete p;
	delete q;
	system("pause");
	return 0;
}

実行結果:
        
        
      ~
      ~
       ...

deleteをオブジェクトに適用した後、オブジェクトにどのようにアクセスしてもエラーであり、このエラーはチェックできません.
特に、配列例については、
#include<iostream>
using namespace std;

class Test
{
public:
	Test(){cout << "        "<<endl;};
	~Test(){cout << "      ~" <<endl;}
};

void f(int size)
{
    Test* t1 = new Test;
    delete t1;

    Test* t2 = new Test[size];
    delete[] t2;
}

int main()
{
	f(3);

	system("pause");
	return 0;
}

実行結果:
        
      ~
        
        
        
      ~
      ~
      ~
       ...

参考資料:C++プログラミング言語(C++の親)