- malloc() 函数在 C 语言中就出现了,在 C++ 中仍然存在,但建议尽量不要使用 malloc() 函数。new 与malloc() 函数相比,其主要的优点是,new 不只是分配了内存,它还创建了对象。
- 只有malloc创建的指针对象是可以通过free去释放内存的,如果malloc创建了指针变量ptr_a,然后将ptr_a的值赋值给另一个指针变量 ptr_b ,然后free(ptr_b) 是行不通的。只能去 free那个被 malloc 创建出来的指针变量。new 也是这样。
code
#include <iostream>
#include <memory>
#include <string.h>
template <typename T,int N>
class Array
{
public:
Array()
{
data_ = (T*)malloc(sizeof(T)*N);
bytes_ = sizeof(T)*N;
}
~Array()
{
free(data_);
std::cout << "array destroy ......" << std::endl;
}
void info()
{
std::cout << "first of this array is " << data_[0] << std::endl;
std::cout << "length this array is " << (int)(bytes_ / sizeof(T)) << std::endl;
for (int i=0;i<this->size();i++)
{
std::cout << " -> " << data_[i];
}
std::cout << "\n";
}
void copy(T* data,size_t num_eles)
{
data_ = (T*)malloc(num_eles * sizeof(T));
for (int i=0;i<num_eles;i++)
{
data_[i] = data[i];
}
bytes_ = num_eles * sizeof(T);
}
void new_size(size_t n)
{
if (n != size())
{
T* temp = data_;
data_ = (T*)malloc(sizeof(T)*n);
if (n < size())
{
for (int i = 0 ;i < n ; i++)
{
data_[i] = temp[i];
}
}
else
{
for (int i = 0 ;i < size() ; i++)
{
data_[i] = temp[i];
}
for (int i = size() ;i < n ; i++)
{
data_[i] = 0;
}
}
bytes_ = n * sizeof(T);
}
}
size_t size()
{
return (int)(bytes_ / sizeof(T)) ;
}
T& operator[](int i)
{
return data_[i];
}
private:
T* data_;
size_t bytes_;
};
template<typename T, int n>
void array_info(std::shared_ptr<Array<T,n>> p)
{
std::cout << "array_info use_count() = " << p.use_count() << std::endl;
}
template<typename T, int n>
void delete_arr(Array<T,n>* p)
{
delete p;
}
int main()
{
auto arr_p = std::make_shared<Array<int,10>>();
int arr2[] = {3,4,5,6,7};
arr_p->copy(arr2,5);
arr_p->info();
array_info(arr_p);
std::cout << "use_count() = " << arr_p.use_count() << std::endl;
auto new_a = new Array<int,10>();
delete_arr(new_a);
auto new_arr = new int[10];
delete []new_arr;
auto aa = new int(10);
delete aa;
}
|