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

本文探讨了在C++中使用vector容器时,插入对象与插入指针的不同之处。通过具体代码实例,展示了两种方式在内存分配、拷贝构造及析构过程中的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.youkuaiyun.com/q191201771/article/details/6120315

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值