【发布时间】:2014-01-22 16:22:09
【问题描述】:
作为练习,我尝试在不使用模板的情况下编写类似std::vector 的类。它拥有的唯一类型是std::string。
下面是strvec.h 文件:
class StrVec
{
public:
//! Big 3
StrVec():
element(nullptr), first_free(nullptr), cap(nullptr)
{}
StrVec(const StrVec& s);
StrVec&
operator =(const StrVec& rhs);
~StrVec();
//! public members
void push_back(const std::string &s);
std::size_t size() const { return first_free - element; }
std::size_t capacity() const { return cap - element; }
std::string* begin() const { return element; }
std::string* end() const { return first_free; }
void reserve(std::size_t n);
void resize(std::size_t n);
//^^^^^^^^^^^^^^^^^^^^^^^^^^^
private:
//! data members
std::string* element; // pointer to the first element
std::string* first_free; // pointer to the first free element
std::string* cap; // pointer to one past the end
std::allocator<std::string> alloc;
//! utilities
void reallocate();
void chk_n_alloc() { if (size() == capacity()) reallocate(); }
void free();
void wy_alloc_n_move(std::size_t n);
std::pair<std::string*, std::string*>
alloc_n_copy (std::string* b, std::string* e);
};
string*、element、first_free、cap 这三个可以认为是:
[0][1][2][3][unconstructed elements]
^ ^ ^
element first_free cap
在实现成员resize(size_t n)时,我遇到了问题。比如说,v.resize(3) 被调用。因此,指针first_free 必须向前移动一位并指向[3]。比如:
[0][1][2][3][unconstructed elements]
^ ^ ^
element first_free cap
我的问题是我应该如何处理[3]?让它原封不动吗?或者像这样销毁它:
if(n < size())
{
for(auto p = element + n; p != first_free; /* empty */)
alloc.destroy(p++);
first_free = element + n;
}
这里需要代码alloc.destroy( somePointer)吗?
【问题讨论】:
标签: c++ string memory-management