c++的默认构造函数 VS 深拷贝(值拷贝) 与 浅拷贝(位拷贝)
C++默认为类生成了四个缺省函数:
A(void); // 缺省的无参数构造函数 A(const A &a); // 缺省的拷贝构造函数 ~A(void); // 缺省的析构函数 A & operate =(const A &a); // 缺省的赋值函数
这不禁让人疑惑,既然能自动生成函数,为什么还要程序员编写?
原因如下:
(1)如果使用“缺省的无参数构造函数”和“缺省的析构函数”,等于放弃了自主“初始化”和“清除”的机会,C++发明人Stroustrup的好心好意白费了。
(2)“缺省的拷贝构造函数”和“缺省的赋值函数”均采用“位拷贝”而非“值拷贝”的方式来实现,倘若类中含有指针变量,这两个函数注定将出错。
缺省的拷贝构造函数与缺省的赋值函数的区别是:
背后实现原理:前者是在返回的时候复制并创建,后者是已经创建过对象了,只是用来重新赋值而已.
调用方式:相同的.
#include <iostream> #include <cstdio> #include <cstring> using namespace std; class String { public: String(const char *str=NULL); String(const String &other); String & operator=(const String &other); ~String(); private: char *m_data; }; /* *普通构造函数 *构造函数首先根据一个字符串常量创建一个String对象。 *这个构造函数首先分配了足够的内存,然后把这个字符串常量复制到这块内存 */ String::String(const char *str) { cout<<" CCC normal "<<endl; if (str == NULL){ m_data = new char[1]; *m_data = '\0'; }else{ int length = strlen(str); m_data = new char[length]; strcpy(m_data, str); } } String::~String() { //当类的左右域超过范围时, 清理所有开辟的内存 delete m_data; } /* *拷贝构造函数 *所有需要分配系统资源的用户定义类型都需要一个拷贝构造函数 *它可以在函数调用中以传值得方式传递一个String类型的参数 *并且在当一个函数以值得形式返回String对象时实现“返回时复制” */ String::String(const String &other) { cout<<" CCC copy "<<endl; int length = strlen(other.m_data); m_data = new char(length + 1); strcpy(m_data, other.m_data); } /* *赋值函数实现字符串的传值活动 */ String & String::operator =(const String &other) { cout<<" CCC equal "<<endl; if (this == &other) return *this; delete[] m_data; int length = strlen(other.m_data); m_data = new char[length + 1]; strcpy(m_data, other.m_data); return *this; } int main() { String MyString("My first String test!"); String MyString2, MyString3 = MyString; MyString2 = MyString; return 0; }