c++ - 在 push_back 中调用 copy_backward 会发生什么?

标签 c++ stl

我最近在看 SGI STL 的源代码。

而且我知道 vector.push_back 会调用 insert_aux,而 insert_aux 会调用 copy_backward

void push_back(const T& x){
    ...
    insert_aux(end(),x);
}

void insert_aux(iterator position, const T& x){
    if (finish != end_of_storage) {
         ...
         ++finish;
         T x_copy = x;
         copy_backward(position, finish - 2, finish -1);
    }
    ...   
}

最后一句,我理解的positionfinish - 1,那怎么调用back_backward when (position >完成 - 2)?

会发生什么?

最佳答案

您省略了重要的代码。

void push_back(const Tp& x) {
    if (finish != end_of_storage) {
        construct(finish, x);
        ++_M_finish;
    }
    else
        insert_aux(end(), x);
}

insert_aux 仅在 finish == end_of_storage 时才会在此处调用。如果此条件为 true,则在 insert_aux 中采用另一个分支来分配新存储:

void insert_aux(iterator position, const Tp& x) {
    if (finish != end_of_storage) {
       ...
    } else {
        const size_type old_size = size();
        const size_type len = old_size != 0 ? 2 * old_size : 1;
        iterator new_start = allocate(len);
        iterator new_finish = new_start;
        new_finish = uninitialized_copy(start, position, new_start);
        construct(new_finish, x);
        ++new_finish;
        new_finish = uninitialized_copy(position, finish, new_finish);
        destroy(begin(), end());
        deallocate(start, end_of_storage - start);
        start = new_start;
        finish = new_finish;
        end_of_storage = new_start + len;
    }
}

insert_aux() 中的第一个分支只是将尾部向右移动一个元素,以便为要插入的元素腾出一个空位。这只有在我们有足够的空间容纳它时才会发生。

关于c++ - 在 push_back 中调用 copy_backward 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016106/

相关文章:

c++ - 为什么我不能用 std::unordered_map 替换 std::map

c++ - C++ std::string 中是否有任何函数可以计算两个字符串的相同起始字符总数或任何最佳方法

java - 尝试将 TCHAR 类型发送到接受字符串作为参数的 java 函数时,jvm 崩溃

c++ - 如何在 C++ 中将字符串转换为具有 6 位精度的 double ?

带 while 循环的 C++ 数组

c++ - 奇怪的析构函数调用顺序

c++ - QT 中信号和槽的清晰命名

c++ - std::swap 中不需要的析构函数调用

c++ - 如何将 std::string 与采用 char[] 缓冲区的 Win32 函数混合?

c++ - C++ 中的签名保留装饰器模式?