现在的位置: 首页 > 综合 > 正文

allocator和new/delete不能混搭使用

2018年05月25日 ⁄ 综合 ⁄ 共 1711字 ⁄ 字号 评论关闭

    看《C++Primer》看到了第18章,这章新讲解了allocator用于分配内存并初始化。打算练练手,于是把之前写好的模拟STL的vector模板做了下修改,用allocator类来管理内存。但只替换了new的部分,delete部分嫌麻烦,暂且不替换。

    下面是出错的源程序:

#include <string>
#include <iostream>
#include <allocators>
using namespace std;

#ifndef VectorH
#define VectorH

namespace ls{

template<class T>
class Vector
{
public:
	//  myIterator;
	typedef  T* myIterator ;	
	Vector();
	void push_back(T &data);
	T& operator[](int index);
	int Size();
	int Capacity();
	myIterator begin() {return head;}
	myIterator end(){return alloc;}

private:
	int size;	//实际已经使用的元素的个数
	int capacity; //容器可以存储的元素的个数
	T* head,	//数组头指针 
		 *alloc;	//当前第一个可分配的指针
	allocator<T> allocat;
};

template<class T> 
Vector<T>::Vector()
{
	capacity = 5;
	//head = new T[capacity];

	//开辟capacity个对象的空间,但不负责初始化
	head = allocat.allocate(capacity);
	alloc = head;
}

template<class T> 
void Vector<T>::push_back(T &data)
{
	//空间不够则扩容
	if(alloc == head + capacity)
	{
		int newCapacity = capacity + 10;
		//T *newHead = new T[newCapacity];
		T *newHead = allocat.allocate(newCapacity);

		//for(int i=0; i<capacity; i++) *(newHead + i) = *(head + i);
		uninitialized_copy(head, head + capacity, newHead);
		
		delete[] head; //释放旧空间的内容
		//混搭使用造成出错

		/*
		必须这样释放内存才可!
		for(int i=0; i<capacity; ++i)
			allocat.destroy(head + i);
		allocat.deallocate(head, capacity);
		*/

		head = newHead;
		alloc = newHead + capacity;
		capacity = newCapacity;
	}

	//*alloc = data;
	allocat.construct(alloc, data);
	alloc ++;
}

template<class T> 
T& Vector<T>::operator[](int index)
{
	if(index < Size())	return *(head + index);
	else cout << "error";
}

template<class T> 
int Vector<T>::Size()
{
	return alloc - head;
}

template<class T> 
int Vector<T>::Capacity()
{
	return capacity;
}

/*
为什么不能放在类体外定义?
template<class T> 
Vector<T>::myIterator Vector<T>::begin()
{
	return head;
}

template<class T> 
Vector<T>::myIterator Vector<T>::end()
{
	return alloc;
}*/

}//end namespace

#endif

   《C++primer》也并没有讲解没什么不能混搭,我自己猜测错误原因是这个样子,于是把delete部分改成了allocator的撤销风格操作。得以正常运行,没有运行时错误了。

抱歉!评论已关闭.