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