STL std::vector 的自定义实现
我正在为没有 STL 构建但有模板支持的平台编写
我正在开发自己的 std::vector 实现。
template<typename T> class Array
{
private:
T * buffer;
int count;
int capacity;
public:
Array() : buffer(0), count(0), capacit(0) { }
~Array() { if(buffer) delete[] buffer; }
void IN_ANY Reserve(const int capacity)
{
if(capacity >= count)
{
T * newBuff = new T[capacity];
if(capacity > count)
memset(newBuff+count, 0, (capacity-count) * sizeof(T));
memcpy(newBuff, buffer, count * sizeof(T));
if(buffer)
delete [] buffer;
buffer = newBuff;
this->capacity = capacity;
}
}
// Other methods...
}
当 T 具有非简单的构造函数、非简单的析构和重载的运算符=时,问题就会出现。然后,当为数组保留额外内存时,将调用 T 的析构函数,而不是构造函数。但不是复制构造函数(因为我使用了 memcpy)。如何改进 Reserve 方法?
I am writing for platform that does not have build in STL but do have templates support
I am working on my own std::vector implementation.
template<typename T> class Array
{
private:
T * buffer;
int count;
int capacity;
public:
Array() : buffer(0), count(0), capacit(0) { }
~Array() { if(buffer) delete[] buffer; }
void IN_ANY Reserve(const int capacity)
{
if(capacity >= count)
{
T * newBuff = new T[capacity];
if(capacity > count)
memset(newBuff+count, 0, (capacity-count) * sizeof(T));
memcpy(newBuff, buffer, count * sizeof(T));
if(buffer)
delete [] buffer;
buffer = newBuff;
this->capacity = capacity;
}
}
// Other methods...
}
The problem comes when T has non-trival constructor, non-trival destruction and overloaded operator=. Then, when Reserving additional memory for array, destructors for T will be called, and than constructors. But not copy constructor (since I used memcpy). How could I improve Reserve method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要自己动手——使用 STLPort。 http://sourceforge.net/projects/stlport/
这是一个免费且高度可移植的 STL 实现。
Don't roll your own--use STLPort. http://sourceforge.net/projects/stlport/
It's a free and highly portable STL implementation.
如果您确实想了解如何实现 STL 的大部分内容,请阅读 PJ Plauger、Alexander Stepanov、Meng Lee 和 David R. Musser 编写的“The C++ Standard Template Library”一书。
除了使用和一些标准解释之外,还讨论了如何实现 STL 的大部分内容。这是一本相当古老的书,但对于了解其幕后发生的事情非常有趣。
如果您不太想知道如何做到这一点,而只是想完成它,请选择有关查看源锻造项目的其他答案之一。
If you really want to know how to implement big parts of the STL, go get the "The C++ Standard Template Library" book by P.J. Plauger, Alexander Stepanov, Meng Lee, and David R. Musser.
Along with use and some standards interpretation is also goes over how to implement large parts of the STL. It is a fairly old book, but very interesting for seeing what goes on under the covers.
If you don't so much want to know how to do it, but more just want it done, go with one of the other answers about looking at source forge projects.
我正在寻找的答案是新的安置
The answer I was looking for was placement new