2012-12-21 37 views
1

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

// 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; 
    } 
} 

行为:

$ 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 

每个push_back执行拷贝的 “未定义” 数目(其中,必须执行仅一个副本)。

这是怎么回事?

回答

3

矢量像数组一样分配连续内存。如果内存末尾没有更多空间,则必须重新分配整个向量。在此之后,它将从旧地点复制到新地点并删除旧地点。

可以初始化它能够容纳至少5个元素,所以西港岛线是没有内存分配,并在你的榜样复制:

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

您的代码将创建长度为5的载体,没有能力5。 – Quentin

1

A push_back可能会导致vector增长超出其分配的存储,这会导致重新分配,这会导致内容被复制。