我想了解std::vector<T>::push_back和std::vector<T>::pop_back是如何在分配的内存中创建和销毁对象的?
我使用了google,我发现人们只是使用size和capacity来限制对内部动态数组的访问,但我认为这并不是标准实现中真正的工作方式
注意:,我不要求标准实现,因为它很复杂,但是我希望能为这种方法提供一个基本的实现
编辑:我想出了如何实现我自己的自定义分配器
为了简单起见,我将只展示自定义分配器之外的重要功能
template <typename T>
T* allocate(std::size_t count) {
return static_cast<T*>(::operator new(count * sizeof(T)));
}
template <typename T>
void deallocate(T* ptr, std::size_t count) {
operator delete(ptr);
}
template <typename U, typename... Args>
void construct(U* ptr, Args&&... args) {
new(ptr) U(std::forward<Args>(args)...);
}
template <typename U>
void destroy(U* ptr) {
ptr->~U();
}然后,在我自己定义的向量中使用,如下所示
int* buff = allocate<int>(8);
// This is like:
// std::vector<int> vec;
// vec.reserve(8);
int* last = &buff[0];
construct<int>(last, 32);
// This is like:
// vec.push_back(32);
++last;
construct<int>(last, 12);
// This is another push
// vec.push_back(12);
destroy(last);
--last;
// This is like:
// vec.pop_back();
deallocate(buff, 8);
// This shoud be in:
// ~vector();如果漏掉了什么..。谢谢
发布于 2016-06-06 18:31:18
所有带有分配器的标准容器都在使用分配器来构造或销毁元素:
23.2.1 3一般集装箱要求(N4296)
对于声明allocator_type的受此子子句影响的组件,存储在这些组件中的对象应使用allocator_traits::construct函数构造,并使用allocator_traits::destroy函数销毁。
标准库中的默认分配器是使用新位置来构造和调用析构函数来销毁元素:
20.7.9 11和12默认分配器(N4296)
template <class U, class... Args>
void construct(U* p, Args&&... args);影响::新的((void *)p) U(std::forward(Args).)
template <class U>
void destroy(U* p);效应: p-> ~ U()
https://stackoverflow.com/questions/37663859
复制相似问题