Vector push_back calls copy_constructor more than once?

I'm a bit confused about how the push_back vector works with the following snippet. I expected the copy constructor to be called only twice, but the output suggests otherwise. Is this an internal internal restructuring that leads to such behavior.

Conclusion:

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);
+4
source share
5 answers

What's happening:

  • xinserted through push_back. One copy occurs: the newly created element is initialized with an argument. my_inttaken as zero, because the default constructor xinitialized it like this.

  • : push_back 'd; , . Myint 1 ; ( my_int - ... my_int 0 ), x ( 1). x my_int , .

, - . , . , .

, , :

myints.reserve(2); // Now two elements can be inserted without reallocation.

, :

myints.emplace_back(0);

"emplaces" - emplace_back , - - .

1 , .

+8

push_back, . , myints.capacity() push_back, 1.

+3

, std::vector. , push_back , . push_back, . , , . .

, :

vector<Myint> myints;
myints.reserve( 2 );
+3

... . , bean , "":

#include <iostream>
#include <vector>
using namespace std;

class Myint
{
private:
    int my_int;
public:
    explicit Myint(int value = 0) : my_int(value) 
    {
        cout << "Inside default " << endl;
    }
    Myint(const Myint& x) : my_int(x.my_int)
    {
        cout << "Inside copy with my_int = " << x.my_int << endl;
    }
    Myint(const Myint&& x) noexcept : my_int(x.my_int) {
        cout << "Inside move with my_int = " << x.my_int << endl;
    } 
};

int main() {
    vector<Myint> myints;
    myints.reserve(2);

    myints.emplace_back(0);
    myints.emplace_back(1);

    // your code goes here
    return 0;
}

:

Inside default 
Inside default

- noexcept ... reserve, , :

Inside default 
Inside default 
Inside move with my_int = 0

. , "" "" , .

+3

, .

. : fooobar.com/questions/914432/...

Or this answer due to the need to create a copy: fooobar.com/questions/918809 / ...

0
source

All Articles