简体   繁体   English

为什么这个程序有这种行为(push_back)?

[英]Why this program has this behaviour (push_back)?

The code: 编码:

// test2.cpp

#include <vector>
#include <iostream>

struct test_class
{
    test_class() = default;

    test_class(const test_class& t)
    {
        std::cout << "Copied" << std::endl;
    }
};

int main()
{
    test_class a;
    std::vector<test_class> v;

    for (int i = 0; i < 5; ++i) {
        v.push_back(a);
        std::cout << std::endl;
    }
}

The behaviour: 行为:

$ g++ --version | grep g++
g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2
$ g++ -std=c++11 test2.cpp
$ ./a.out
Copied

Copied
Copied

Copied
Copied
Copied

Copied

Copied
Copied
Copied
Copied
Copied

Each push_back performs an "undefined" number of copies (where only one copy must be performed). 每个push_back执行“未定义”的副本数(其中只需执行一个副本)。

What is going on here? 这里发生了什么?

The vector allocates continuous memory just like an array. 向量像数组一样分配连续内存。 If there is no more space at the end of the memory it has to reallocate the whole vector. 如果内存末尾没有更多空间,则必须重新分配整个向量。 After this it will copy the elements from the old place to the new and delete the old. 在此之后,它会将元素从旧位置复制到新位置并删除旧元素。

You can initialize it to be able to hold at least 5 elements, so there wil be no memory allocation and copy in your example: 您可以初始化它以至少能容纳5个元素,因此在您的示例中不会有内存分配和复制:

std::vector<test_class> v(5);

push_back可能导致vector增长超出其分配的存储空间,从而导致重新分配,从而导致内容被复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM