拜读Effective C++ 有感

本文探讨了C++中默认编写的函数,包括构造函数、析构函数等,并通过实例对比了深复制与浅复制的区别。对于程序员理解C++类的行为至关重要。

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

毕业参加工作已经半年了,感觉这半年的状态和自己在学校时候想的还是有点不一样的,总是少了点向上的冲劲,在工作之余,也没了给自己充电的动力了,觉得真的很不应该,买了好久的Effective C++,随手拿过来的翻翻,总觉得醍醐灌顶。可往往在实际的工作中还是会犯一些错误,现在决定把读下来的感悟写下来,细细品味,正所谓编程是一项艺术而不仅仅是一项技术。

1.了解C++默认编写并调用那些函数。

这些问题在找个工作面试的时候经常被问起。如果定义一个空类,比如 CEmpty:

class CEmpty
{
};

编译器会为这个类增加  默认构造函数,析构函数,拷贝构造函数,copy assignment(拷贝赋值函数)。其中默认构造函数和析构函数不提,主要注意的是增加的析构函数时非virtual的。至于拷贝构造函数和copy assignment函数是单纯的将源对象的每个非静态成员变量进行拷贝。比如如下的一个代码:

using namespace std;
class CExampleStr
{
public:	
	CExampleStr (const string &strName);


	~CExampleStr();
private:
	string m_strName;
};
CExampleStr::CExampleStr(const string & strName)
{
	strName = strName;
};
using namespace std;
class CExampleChar
{
public:
	CExampleChar(const char *pName, int nLen);
	~CExampleChar();
private:
	char *m_pName;
	int   m_nLen;
};


CExampleChar::CExampleChar(const char *pName, int nLen)
{
	if(NULL == pName || nLen == 0)
	{
		return;
	}
    m_pName = new char[nLen+1];
    m_pName[nLen] = "\0";
    memcpy(m_pName,pName, nLen);
}
CExampleChar::~CExampleChar()
{
	delete []m_pName;
}

显然对于第一个来说:

string strName("张三");

CExampleStr exampleName1(strName);

//拷贝构造函数

CExampleStr exampleName2(exampleName1);

//复制构造函数

CExampleStr exampleName3 = exampleName1;

当调用拷贝构造函数时,会拷贝CExampleStr的成员变量,也就是会进行如下的操作 :

exampleName2.m_strName = exampleName1.m_strName;

也就是调用了string类型的复制构造函数,string类的复制构造函数如下:

String& String::operator =(const String &other) 
{
    if (this==&other)//
当地址相同时,直接返回;
        return *this; 
 
    delete [] m_data;//
当地址不相同时,删除原来申请的空间,重新开始构造;

    int length=sizeof(other.m_data);
    m_data=new [length+1];
    strcpy(m_data,other.m_data);

    return *this; 
}

显然是种“深复制”,所有上述的用法不会出现问题。然而对于下面的CExampleChar 类的用法就会出现问题 

CExampleChar exampleChar1(strName.c_str(), strName.length);

//拷贝构造函数

CExampleChar  exampleChar2(exampleChar1);

CExampleChar exampleChar2 = exampleChar1;

对于exampleChar2(exampleChar1),其实执行的是

exampleChar2.m_pName = exampleChar1.m_pName;这个时候只是进行了指针的复制(浅复制)






                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值