C++为我们提供了安全的内存空间申请方式与释放方式,但是new与delete表达式却是把空间的分配回收与对象的构建销毁紧紧的关联在一起。实际上,作为与C语言兼容的语言,C++也为我们提供了更加底层的内存操作方式的。
谈C++就离不开STL,考虑一下vector<>类的机制,为了高效率的增加与删除元素,它并不会在我们每次进行添加或删除操作时进行内存的分配与回收,而是会提前预留下一片空间。我们通过size函数可以得到容器内元素的个数,通过capacity函数则可以得到该容器的实际大小。实际上每个容器都有自己的Allocator类,用于进行空间的分配与回收,对象的构造与销毁。下面的代码来自与《C++ primer》,是vector类的push_back函数的一种可能实现方式:
template
void Vector::push_back(const T& t)
{
// are we out of space?
if (first_free == end)
reallocate(); // gets more space and copies existing elements to it
alloc.construct(first_free, t);
++first_free;
}
first_free指向容器中第一个空闲的块,如果已经没有空闲块了,则通过reallocate函数重新分配。alloc是Alloctor
当我们使用new表达式,来调用拷贝构造函数时实际上时伴随着空间的分配的。那么Allocator是怎么做到的呢?实际上它是调用了C++的一个内置的操作符:
void *operator new(size_t); // allocate an object
void *operator new[](size_t); // allocate an array
new (place_address) type
new (place_address) type (initializer-list)
这写重载操作符函数可以进行内存的分配以及在指定的内存空间进行对象的构造。需要注意的是它们并非new表达式,new表达式是不可以被重载的,实际上new表达式底层也就是调用了这些重载函数的。前两个用内存的分配,后两个则用于对象的构造。Alloctor
new (first_free) T(const T& t);
template void Vector::reallocate() {
// compute size of current array and allocate space for twice as many elements
std::ptrdiff_t size = first_free - elements;
std::ptrdiff_t newcapacity = 2 * max(size, 1);
// allocate space to hold newcapacity number of elements of type T
T* newelements = alloc.allocate(newcapacity);
// construct copies of the existing elements in the new space
uninitialized_copy(elements, first_free, newelements);
// destroy the old elements in reverse order
for (T *p = first_free; p != elements; /* empty */ )
alloc.destroy(--p);
// deallocate cannot be called on a 0 pointer
if (elements)
// return the memory that held the elements
alloc.deallocate(elements, end - elements);
// make our data structure point to the new elements
elements = newelements;
first_free = elements + size;
end = elements + newcapacity;
}
这个实现就稍微复杂一点了,逻辑上我就不说了,着重说明一下其中几个函数的使用吧。首先是Alloctor
return operator new[](newcapacity * sizeof(T));
template
ForwardIterator
uninitialized_copy ( InputIterator first, InputIterator last,
ForwardIterator result );
然后是关于Alloctor
接下来是关于Alloctor
void *operator delete(void*); // free an object
void *operator delete[](void*); // free an array