我对矢量push_back行为的方式有点困惑,使用下面的代码片段我预计复制构造函数只能被调用两次,但输出建议不然.是矢量内部重组导致这种行为.
输出:
Run Code Online (Sandbox Code Playgroud)Inside default Inside copy with my_int = 0 Inside copy with my_int = 0 Inside copy with my_int = 1
class Myint
{
private:
int my_int;
public:
Myint() : my_int(0)
{
cout << "Inside default " << endl;
}
Myint(const Myint& x) : my_int(x.my_int)
{
cout << "Inside copy with my_int = " << x.my_int << endl;
}
void set(const int &x)
{
my_int = x;
}
}
vector<Myint> myints;
Myint x;
myints.push_back(x);
x.set(1);
myints.push_back(x);
Run Code Online (Sandbox Code Playgroud)