STL Vector Selection

I was wondering why vector patterns perform two distributions when only one seems necessary.

For example:

#include <vector>
#include <iostream>

class A {
    public:
         A(const A &a) {
            std::cout << "Calling copy constructor " << this << " " << &a << "\n";
        }
         A() {
            std::cout << "Calling default constructor " << this << "\n";
        }
        ~A() {
            std::cout << "Calling destructor " << this << "\n"; 
        }
};

int main(int argc, char **argv)
{
    std::vector <A> Avec;

    std::cout << "resize start\n";
    Avec.resize(1);
    std::cout << "resize end\n";

    return 0;
}

Outputs:

resize start
Calling default constructor 0x7fff9a34191f
Calling copy constructor 0x1569010 0x7fff9a34191f
Calling destructor 0x7fff9a34191f
resize end
+3
source share
3 answers

It does not perform two distributions, it creates a default object so that the constructor goes to size, then copies this object to a new position, and then destroys the argument.

If you look at the arguments for resizing:

void resize(n, t = T())

T ( ). ( ). ( ).

+15

, , . , :

vector<A*> Avec;
avec.push_back(new A());

http://www.cplusplus.com/reference/stl/vector/vector/

0

:

  • Avec , " "
  • 0
  • , A ( A, .
0

Source: https://habr.com/ru/post/1710694/


All Articles