《C++ Primer第四版》的operator delete问题

xufei96 xufei96 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
《C++ Primer第四版》中第637页有写到:
operator new和operator delete函数有两个重载版本,没个版本支持相关的new表达式和delete表达式:
void *operator new(size_t); //allocate an object
void *operator new[](size_t); //allocate an array

void *operator delete(void*); //delete memory of an object
void *operator delete[](void*); //delete memory of an array


于是,我写了以下代码:
template<class T>
class Vector{
public:
Vector():elements(0),first_free(0),end(0){}
void push_back(const T&);
void *operator new[](size_t); //allocate an array
void *operator delete[](void*); //delete memory of an array
private:
static std::allocator<T> alloc;
void reallocate();
T* elements; //first element
T* first_free; //behind the last actual element
T* end; //behind vector conent
};

template<class T>
void Vector<T>::push_back(const T& t){
if(first_free==end)
reallocate(); //gets more space and copies existing elements to it
alloc.construct(first_free,t);
++first_free;
}

template <class T>
void Vector<T>::reallocate(){
std::ptrdiff_t size=first_free-elements;
std::ptrdiff_t newcapacity=2*max(size,1);
T* newelements=static_cast<T*>(alloc.operator new[](newcapacity));

uninitialized_copy(elements,first_free,newelements);

for(T *p=first_free;p!=elements;){
alloc.destroy(--p);
}

if(elements)
alloc.operator delete[](elements,end-elements);

elements=newelements;
first_free=elements+size;
end=elements=newcapacity;
}

但是编译后发现出现编译错误:
Error	3	error C2817: return type for 'operator delete' must be 'void'	c:\documents and settings\10170660\my documents\visual studio 2010\projects\cp\cp\namespace3.h	54	1	CP


请问各位大侠,这里是不是C++ Primer的一个错误啊?是不是应该是void operator delete[](void*);这样定义operator delete?
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
xufei96
C++ 语言 65,214 成员 250,514 内容