The difference between inserting objects and inserting pointers in C++ vector

The difference between inserting objects and inserting pointers in C++ vector

1. Insert the object:

#include <vector>
#include <stdio.h>

static int count=0;

class A
{
private:
int m;
public:
    A()
    {
        printf("A(): %d\n",count);
        m = count;
        count++;
    }

    ~A()
    {
        printf("~A()%d\n",m);

    }

    A(const A& other)
    {
        printf("other%d\n",count);
        m = count;
        count++;
    }

};

int main()
{
    A a;
    A b(a);
    A c = a;

    printf("----------\n");

    std::vector<A> vec;
    //vec.reserve(3);
    vec.push_back(a);
    vec.push_back(b);
    vec.push_back(c);

    return 0;
}

Export results;

A(): 0
other1
other2
----------
other3
other4
other5
~A()3
other6
other7
other8
~A()5
~A()4
~A()7
~A()8
~A()6
~A()2
~A()1
~A()0

If you remove the //vec.reserve(3); comment, the output will be:

A(): 0
other1
other2
----------
other3
other4
other5
~A()3
~A()4
~A()5
~A()2
~A()1
~A()0

It can be seen from the first output: the vector container push_backs an object, that is, a copy of the object. In the next push_back, since the memory that the vector initially applied for is not enough, it will apply for space again and may give up the originally applied space, so call The number of copy constructions is more, so we should apply for an estimated value in advance through its member function reserve before using vector. You can rest assured that when the reserved space is not large enough, the vector will still automatically apply for space.

2. Insert pointer:

code show as below:

#include <vector>
#include <stdio.h>

static int count=0;

class A
{
private:
int m;
public:
    A()
    {
        printf("A(): %d\n",count);
        m = count;
        count++;
    }

    ~A()
    {
        printf("~A()%d\n",m);

    }

    A(const A& other)
    {
        printf("other%d\n",count);
        m = count;
        count++;
    }

};

int main()
{
    A *a = new A;
    A *b = new A(*a);
    A *c = new A(*a);

    printf("----------\n");

    std::vector<A*> vec;
    //vec.reserve(3);
    vec.push_back(a);
    vec.push_back(b);
    vec.push_back(c);
    std::vector<A*>::iterator iter = vec.begin();
       for (; iter!=vec.end(); ++iter)
       {
           delete *iter;   //*iter = a , b, c
       }

       vec.clear();
    return 0;
}

The output is as follows:

A(): 0
other1
other2
----------
~A()0
~A()1
~A()2

Reference for this article: https://blog.csdn.net/q191201771/article/details/6120315

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324726323&siteId=291194637