代码:
// 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
执行“未定义”的拷贝数(其中只必须执行一个拷贝)。
这是怎么回事?
最佳答案
vector 就像数组一样分配连续的内存。如果内存末尾没有更多空间,则必须重新分配整个 vector 。之后它将元素从旧位置复制到新位置并删除旧位置。
您可以将其初始化为能够容纳至少 5 个元素,因此在您的示例中不会有内存分配和复制:
std::vector<test_class> v(5);
关于c++ - 为什么这个程序有这种行为(push_back)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13989734/