STL 共通性,使用的是值语义,而不是引用语义

STL 共通性,使用的是值语义,而不是引用语义

其实这句话的意思,STL一般操作的是一个变量的副本,而不是变量本身。这样的话,当一个变量中存在指针指向的空间时,这时就会在使用的时候,产生深拷贝和浅拷贝的问题。所以在使用STL的操作自定义的类型时,需要注意该方面的问题,一般是必须重写无参构造函数,拷贝构造函数,重载=运算符。

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

class teacher
{
public:
    teacher()
    {
        m_pname = new char[1];
        memset(m_pname, 0, 1);
        m_age = 0;
    }
    teacher(const char* name, int age)
    {
        m_pname = new char[strlen(name) + 1];
        memset(m_pname, 0, strlen(name) + 1);
        strcpy_s(m_pname, strlen(name) + 1, name);
        m_age = age;
    }
    ~teacher()
    {
        if (nullptr != m_pname)
        {
            delete[]m_pname;
            m_pname = NULL;
        }
        m_age = 0;
    }
    void print()
    {
        cout << m_pname << ":" << m_age << endl;
    }
    teacher(const teacher& t)
    {
        m_pname = new char[strlen(t.m_pname) + 1];
        memset(m_pname,0, strlen(t.m_pname) + 1);
        strcpy_s(m_pname, strlen(t.m_pname) + 1, t.m_pname);
        m_age = t.m_age;
    }
    //重载等号t3=t2=t1;
    teacher& operator=(const teacher& t)
    {
        if(this == &t)
        {
            return *this;
        }
        //先把t2的就内存释放掉
        if (this->m_pname != NULL)
        {
            delete[]m_pname;
        }
        //根据t1的大小分配内存
        m_pname = new char[strlen(t.m_pname)+1];
        memset(m_pname,0, strlen(t.m_pname) + 1);
        //copy对应的内存
        strcpy_s(m_pname, strlen(t.m_pname) + 1, t.m_pname);
        m_age = t.m_age;
        return *this;

    }
private:
    char* m_pname;
    int m_age;
};
int main()
{
    //teacher t4(); // 无参构造不能加()

    teacher t4;
    t4.print();

    vector<teacher> v1;
    teacher t1("t1",31);
    t1.print();
    //把t1 copy了一份到v1中,就会出现在浅拷贝和深拷贝
    v1.push_back(t1);
    vector<teacher>::iterator iter = v1.begin();
    iter->print();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值