http://blog.csdn.net/eclipser1987/article/details/8024555
為什么C++中不建議使用malloc calloc realloc等C語言函數?因為:這樣分配的空間,返回的指針需要通過free來釋放,但free釋放空間不同于delete,free不會執行析構函數!

/**//*
* File: main.cpp
* Author: Vicky.H
* Email: eclipser@163.com
*/
#include <iostream>
#include <cstdlib>
#include <memory>


class A
{
public:


A()
{
std::cout << "create A" << std::endl;
}


A(const A& o)
{
std::cout << "copy A" << std::endl;
}


~A()
{
std::cout << "delete A" << std::endl;
}
};


/**//*
*
*/

int main(void)
{

char* buf1 = (char*) malloc(10); //
char* buf2 = (char*) calloc(1, 10); // 效果雖然與上面一樣,不同的是,calloc會將空間初始化為0.

free(buf1);
free(buf2);

std::cout << "---------------------------" << std::endl;

// 為什么C++中不建議使用malloc calloc realloc等C語言函數?因為:這樣分配的空間,返回的指針需要通過free來釋放,但free釋放空間不同于delete,free不會執行析構函數!

A* ap = (A*) malloc(sizeof (class A) * 10);
std::uninitialized_fill_n(ap, 10, A());
free(ap); // 調用1次create A ,1次delete A 10次copy A
return 0;
}


---------------------------
create A
copy A
copy A
copy A
copy A
copy A
copy A
copy A
copy A
copy A
copy A
delete A
雖然實例程序,對空間的分配釋放沒有任何錯誤,但在某些情況,比如A類的析構伴隨著某些特殊處理,將導致程序異常!