开发者

Copy constructor called many times when data is inserted in vector

开发者 https://www.devze.com 2023-03-12 06:47 出处:网络
#include <iostream> #include <vector> using namespace std; class base { int x; public: base(int k){x =k; }
#include <iostream>
#include <vector>
using namespace std;
class base
{
    int x;
public:
    base(int k){x =k; }
    void display()
    {
        cout<<x<<endl;
    }

    base(const base&)
    {
        cout<<"base copy constructor:"<<endl;
    }
};
int main()
{
    vector<base> v;
    base obase[5]={4,14,19,24,29};
    for(int i=0; i<5; i++)
    {
        v.push_back(obase[i]);
    }

}

When data is inserted into vector, copy to that data goes to vector using the copy constructor.

When i run this program,

  1. for the first inser开发者_JS百科tion (i=0), one time copy constructor is called.
  2. for the second insertion (i=1), two times copy constructor is called
  3. for the third insertion (i=3), three times copy constructor is called
  4. for the fourth insertion (i=3), four times copy constructor is called
  5. for the fifth insertion (i=4), five times copy constructor is called

Please any one can tell me why this is happening? For each insertion, shouldn't the copy constructor be called only once?


calls to push_back() increase the size of the vector as necessary, which involves copying of vector's contents. Since you already know that it's going to contain five elements, either v.reserve(5); right before the loop, or use the range constructor:

base obase[5]={4,14,19,24,29};
vector<base> v(obase, obase+5);


Your copy constructor is flawed, you forgot to actually copy the data :)

base(const base& that) : x(that.x)
{
    cout << "base copy constructor\n";
}

Also, if you have a modern compiler, you can write a move constructor and learn something new:

base(base&& that) : x(that.x)
{
    cout << "base move constructor\n";
}


If v needs to resize its internal buffer, it will usually allocate a totally fresh memory area, so it needs to copy all the objects that were previously in the vector to the new location. This is done using regular copying, so the copy constructor is invoked.

You should call reserve() on the vector to reserve storage upfront if you can estimate how many elements you are going to need.

Note that the resize/growth behaviour of std::vector is implementation-dependent, so your code sample will produce different results with different standard library implementations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号