c++ - Push_back和pop_back的实现

标签 c++ push-back

我想了解如何 std::vector<T>::push_backstd::vector<T>::pop_back在分配的内存中创建和销毁对象?

我用谷歌,发现人们只是玩sizecapacity限制对内部动态数组的访问,但我认为这并不是标准实现中真正的工作方式

注意:我不要求标准实现,因为它会很复杂,但我希望这种方法的基本实现


编辑:我想出了如何实现我自己的自定义分配器

为了简单起见,我将仅显示自定义分配器中的重要函数

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();
}

然后我在我自己定义的 vector 中使用像这样的东西

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();

如果遗漏了什么,请检查一下...谢谢

最佳答案

所有带有分配器的标准容器都使用分配器来构造或销毁元素:

23.2.1 [3] 一般容器要求 (N4296)

For the components affected by this subclause that declare an allocator_type, objects stored in these components shall be constructed using the allocator_traits::construct function and destroyed using the allocator_traits::destroy function

标准库中默认的分配器是使用placement new来构造并调用析构函数来销毁元素:

20.7.9 [11] 和 [12] 默认分配器 (N4296)

template <class U, class... Args>
void construct(U* p, Args&&... args);

效果:::new((void *)p) U(std::forward(args)...)

template <class U>
void destroy(U* p);

效果:p-> ~ U()

关于c++ - Push_back和pop_back的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37663859/

相关文章:

c++ - delete[] 是否释放整个内存块?

Android C++ 应用程序在链接到共享库阶段崩溃

c++ - Vector<char*> push_back 覆盖所有条目

c++ - 在基于范围的 for 循环期间插入到 std::list 的后面

C++ Push_back vector<struct>MyVector 和错误 C2664

c++ - 在 std::list 上 push_back 或删除时出现段错误

c++ - 如何在main之前强制初始化静态局部变量?

c++ - 如何与android的静态boost库链接?

c++ - 在 WPF 中托管 native 控件

c++ - 如何push_back到子 vector ?