相关疑难解决方法(0)

矢量push_back不止一次调用copy_constructor?

我对矢量push_back行为的方式有点困惑,使用下面的代码片段我预计复制构造函数只能被调用两次,但输出建议不然.是矢量内部重组导致这种行为.

输出:

Inside default

Inside copy with my_int = 0

Inside copy with my_int = 0

Inside copy with my_int = 1
Run Code Online (Sandbox Code Playgroud)
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)

c++ stdvector

6
推荐指数
1
解决办法
1225
查看次数

标签 统计

c++ ×1

stdvector ×1