C++ vector插入对象与插入指针的区别

C++ vector插入对象与插入指针的区别

1.插入对象:

#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;
}

輸出結果爲;

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

若去掉 //vec.reserve(3); 注释,输出结果:

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

由第一个输出可见:vector容器push_back一个对象,即是对该对象的拷贝,在下一次push_back时,由于vector开始申请的内存不够使用,它会再次申请空间并可能放弃原来申请的空间, 这样调用的拷贝构造次数就更多了, 所以我们在使用vector前应该通过它的成员函数reserve事先申请一个我们估计的值, 你可以放心, 当reserve的空间不够大时, vector仍然会自动申请空间。

2.插入指針:

代码如下:

#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;
}

输出结果如下:

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

本文参考:https://blog.csdn.net/q191201771/article/details/6120315

猜你喜欢

转载自blog.csdn.net/every_day_/article/details/80051323