//11,在operator=中处理"自我赋值"
class Bitmap{};
class Widget
{
void swap(Widget &rhs); //交换*his和rhs的数据
private:
Bitmap *pb;
};
Widget & Widget::operator=(const Widget &rhs)
{
Widget temp(rhs); //为rhs数据制作一份复件
swap(temp); //将*this数据和上述复件的数据交换
return *this;
}
//12,赋值对象时勿忘其每一个成分
//<1>,确保复制"对象内的所有成员函数"及"所有的base class成分"
//<2>,不要尝试以某个拷贝函数实现另一个拷贝函数
//13,已对象管理资源,使用"智能指针"
class Investment{...}
void fun1()
{
Investment *pInv = createInvestment(); //返回对象指针
delete pInv;
}
void fun2()
{
//使用智能指针,auto_ptr的析构函数自动删除pInv
//别让多个auto_ptr同时指向同一个对象
std::auto_ptr<Investment> Pinv(createInvestment());
}
//atuo_ptr不正确用法,auto_ptr被销毁时会自动删除它所指之物
void fun3()
{
std::auto_ptr<Investment> pInv1(createInvestment()); //pInv1指向 createInvestment返回物
std::auto_ptr<Investment> pInv2(pInv1); //现在pInv2指向对象,pInv1被设置为null
pInv1 = pInv2; //现在pInv1指向对象,pInv2被设为null
}
//使用shared_ptrs智能指针
void fun4()
{
std::shared_ptr<Investment> pInv1(createInvestment()); //pInv1指向 createInvestment返回物
std::shared_ptr<Investment> pInv2(pInv1); //pInv1和pInv2指向同一个对象
pInv1 = pInv2; //pInv1和pInv2指向同一个对象
}
//14,在资源管理类中小心copying行为
class Lock
{
public:
explicit Lock(Mutex *pm) : mutexPtr(pm)
{
lock(mutexPtr);
}
~Lock()
{
unlock(mutexPtr);
}
private:
Mutex *mutexPtr;
}
Mutex m;
Lock ml1(&m); //锁定m
Lock ml2(ml1); //复制,在使用过程中会出现意想不到的错误,禁止RAII class复制,见条款6
//15,在资源管理类中提供对原始资源的访问
std::tr1::shared_ptr<Investment> pInv(createInvestment()); //条款13
int dayHeld(const Investment *pi);
int days = daysHeld(pInv); //错误,daysHeld需要指针,却给的是tr1::shared_ptr<Investment>的对象
int days = daysHeld(pInv.get()); //正确
//16,使用new 和 delete要使用相同的形式
std::string* stringPtr1 = new std::string;
std::string* stringPtr2 = new std::string[100];
delete stringPtr1; //删除一个对象
delete []stringPtr2; //删除一个由对象组成的数组
//17,以独立语句将newed对象置入智能指针
//18,让接口容易被正确使用,不易被误用
//19,设计class犹如type
//<1>,新的type的对象应该如何被创建和销毁
//<2>,对象的初始化和对象的赋值该有什么样的差别
//<3>,新type的对象如果被passed by value(以值传递),意味着什么
//<4>,什么是type的合法值
//<5>,你的新type需要配合某个继承图系么
//<6>,你的新type需要什么样的转换
//<7>,什么样的操作符和函数对此新type而言是合理的
//<8>,什么样的标准函数应该驳回
//<9>,谁该取用新type的成员
//<10>,什么是新type的"未声明接口"
//<11>,你的新type有多么一般化
//<12>,你真的需要一个新的type么
//20,宁以pass-by-reference-to-const替代pass-by-value
class Person
{
public:
Person();
virtual ~Person();
private:
std::string name;
std::string address;
}
class Student: public Person
{
public:
Student();
~Student();
private:
std::string schoolName;
std::string schoolAddress;
}
bool validateStudent(Student s); //函数以by value方式接受学生
Student plato;
//这样使用会调用"一次student copy构造函数"和"一次student析构函数"
bool platoIsOk = validateStudent(plato); //调用函数
//使用引用
bool validateStudent1(const Student &s);
bool platoIsOk = validateStudent1(plato); //调用函数
11~20条款
最新推荐文章于 2022-11-15 21:00:35 发布