[英]reserve() Implementation for std::vector in STL
从“The C ++ Programming Language,4th ed。,Bjarne Stroustrup”一书中考虑std :: vector :: reserve()的这种实现:
template<class T, class A>
void vector<T,A>::reserve(size_type newalloc)
{
if (newalloc<=capacity()) return;
vector_base<T,A> b {vb.alloc,newalloc}; // get new storage
// (see PS of question for details on vb data member)
T* src = elem; // ptr to the start of old storage
T* dest = b.elem; // ptr to the start of new storage
T* end = elem+size(); // past-the-end ptr to old storage
for (; src!=end; ++src, ++dest) {
new(static_cast<void*>(dest)) T{move(*src)}; // move construct
src–>~T(); // destroy
}
swap(vb,b); // install new base (see PS if needed)
} // implicitly release old space(when b goes out of scope)
注意,在循环中,对于向量中的每个元素,至少对ctor和dtor进行一次调用(如果元素的类具有基数,或者如果类或其基数具有带有ctors的数据成员,则可能触发更多此类调用) 。 (在本书中,for循环实际上是一个单独的函数,但为了简单起见,我将其注入reserve()。)
现在考虑我建议的选择:
template<class T, class A>
void vector<T,A>::reserve(size_type newalloc)
{
if (newalloc<=capacity()) return;
vector_base<T,A> b {vb.alloc,newalloc}; // get new space
memcpy(b.elem, elem, sz); // copy raw memory
// (no calls to ctors or dtors)
swap(vb,b); // install new base
} // implicitly release old space(when b goes out of scope)
对我来说,似乎最终结果是相同的,减去对ctors / dtors的调用。
是否存在这种替代方案失败的情况,如果是这样,那么缺陷在哪里?
PS我认为它不太相关,但这里是vector
和vector_base
类的数据成员:
// used as a data member in std::vector
template<class T, class A = allocator<T> >
struct vector_base { // memory structure for vector
A alloc; // allocator
T* elem; // start of allocation
T* space; // end of element sequence, start of space allocated for possible expansion
T* last; // end of allocated space
vector_base(const A& a, typename A::size_type n)
: alloc{a}, elem{alloc.allocate(n)}, space{elem+n}, last{elem+n} { }
~vector_base() { alloc.deallocate(elem,last–elem); } // releases storage only, no calls
// to dtors: vector's responsibility
//...
};
// std::vector
template<class T, class A = allocator<T> >
class vector {
vector_base<T,A> vb; // the data is here
void destroy_elements();
public:
//...
};
这可能会失败:
只有拥有POD向量时, memcpy()
才有效。
它将失败所有其他类型的对象,因为它不尊重它复制的对象的语义(复制构造)。
问题示例:
memcpy()
将复制原始指针的值,该指针将无法正确更新并继续指向将要释放的内存区域。 shared_ptr
,则对象计数将变得不一致( memcpy()
将复制指针而不增加其引用计数,然后swap()
将确保原始共享指针将在b中,这将被释放,因此共享指针引用计数将递减)。 正如TC在评论中指出的那样,只要向量存储非POD数据, memcpy()
产生UB(未定义的行为)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.