c++ - push_back to std::vector, the copy constructor is repeatedly called
问题描述
With is code, I've got the following output:
A::A() is called
test #1
A::A(const A & other) is called
test #2
A::A(const A & other) is called
A::A(const A & other) is called
test #3
A::A(const A & other) is called
A::A(const A & other) is called
A::A(const A & other) is called
When debugging the code, for the 3 test cases, I found that the 1st invocation to copy constructor is the same (and I think it makes sense): make a copy of the object and push to the vector.
However, additional invocation to the copy constructor is made through "_Umove_if_noexcept".
For test #2, when vec already has ONE entry, it will further invoke ONE time of the copy constructor.
For test #3, when vec already has TWO entry, it will further invoke TWO times of the copy constructor.
This is reproducible on Visual Studio 2017 and gcc 5.4.0.
Why is this happening? Is there a performance issue?
Thanks
#include <iostream>
#include <vector>
class A
{
public:
//constructor
A()
{
a = 10;
std::cout << "A::A() is called" << std::endl;
}
//copy constructor
A(const A& other) : a(other.a)
{
std::cout << "A::A(const A & other) is called" << std::endl;
}
//assignment operator
A& operator=(const A& other)
{
std::cout << "A::operator=(const A & other) is called" << std::endl;
a = other.a;
return *this;
}
public:
int a;
};
int main()
{
std::vector<A> vec;
//A::A() is called
A a;
std::cout << "test #1" << std::endl;
//A::A(const A & other) is called by push_back
vec.push_back(a);
std::cout << "test #2" << std::endl;
//A::A(const A & other) is called
//A::A(const A & other) is called from _Umove_if_noexcept
vec.push_back(a);
std::cout << "test #3" << std::endl;
//A::A(const A & other) is called
//A::A(const A & other) is called from _Umove_if_noexcept
//A::A(const A & other) is called from _Umove_if_noexcept
vec.push_back(a);
std::cin.get();
return 0;
}
解决方案
推荐阅读
- python-3.x - 当损失依赖于输入并通过自定义损失层实现时,如何使用 tf estimator API 为 train_op 设置损失?
- ios - 在 iPad 中显示 ActionSheet
- ffmpeg - 没有 RTSP 的 TCP 上的 RTP(用于在 FFmpeg 中接收)
- windows - 用于检查 Windows 更新的 VB 代码说服务器不可用
- oracle - 异常与 raise_application_error
- javascript - 使用Javascript在图像上绘制画布线不会影响整个区域
- objective-c - 如何在 Objective-C 中测试标准输入功能?
- node.js - 我尝试使用 nodejs 和 mongodb 进行 crud 操作。所有 crud 操作都工作正常。但是 get 方法只显示一个数据而不显示所有数据
- mysql - 如何运行包含大量数据的查询?
- r - 从服务器端调用对数据表应用客户端过滤器