string s1 = "hello";
string s2 = s1; //这时s2没有自己的私有数据,而是共享s1的数据
cout << s1;
cout << s1 + s2; //这时因为是读操作,s2还是没有自己的私有数据,仍旧是共享s1的数据
s2.upper();//将s2的小写转为大写,编译器在此之前,才会将s2构造出私有数据,因为不得不构造一份数据了
string s = "hello world!";
cout << s[1]; //读操作
s[2] = 'd'; //写操作
此条款的含义是超急评估over eager evaluation, 尽早的提前做事。典型的以空间换取时间的做法。
函数中具有明确名字的对象叫局部对象,C++中真正的临时对象是不可见的,这些临时对象。
主要有2种情况发生:
任何时候,只要看到reference-to-const的函数参数,就十分有可能产生一个临时对象。任何时候当你看到函数返回对象的时候,也会产生临时对象。
inline const Rational operator*(const Rational& lhs, const Rational & rhs){
return Rational(lhs.numerator() * rhs.numerator(), lhs.denominator() * rhs.denominator());
}
隐式转换时候,很方便程序员写代码。但是隐式转换会导致产生一个临时对象,影响效率。
比较好的方法时,对于可能的隐式转换都定制重载函数。
class UPInt{
public:
UPInt();
UPInt(int);
};
const UPInt operator+(const UPInt& lhs, const UPInt& rhs);
UPInt upi1, upi2;
UPInt upi3 = upi1 + upi2;
upi3 = 1 + upi1;//这里会进行隐式转换
upi3 = upi2 + 1;//这里会进行隐式转换
修改如下:
const UPInt operator+(const UPInt& lhs, int rhs);
const UPInt operator+(int lhs, const UPInt& rhs);
UPInt upi1, upi2;
UPInt upi3 = upi1 + upi2;
upi3 = 1 + upi1;//这里不会进行隐式转换
upi3 = upi2 + 1;//这里不会进行隐式转换
最好以 operator+= 和operator-=来实现 operator+ 和 operator-,并让函数可以执行返回值优化NRV。
class Rational{
public:
Rational& operator +=(const Rational&rhs);//并已实现
Rational& operator -=(const Rational&rhs);//并已实现
};
//且只需要维护-=,+=等就可以了。
const Rational operator+(const Rational& lhs, const Rational& rhs){
return Rational(lhs) += rhs; //这样写可以实现NRV
}
const Rational operator-(const Rational& lhs, const Rational& rhs){
return Rational(lhs) -= rhs; //这样写可以实现NRV
}
不同的程序库在性能以及效率、实现方式、适用性均有不同表现,选择合适的程序库来契合不同的场景。
将constructor设置为private 或者设置为delete。
class CantBeInstantiated{
private:
CantBeInstantiated();
CantBeInstantiated(const CantBeInstantiated&);
}
或者
class CantBeInstantiated{
public:
CantBeInstantiated() = delete;
CantBeInstantiated(const CantBeInstantiated&) = delete;
}
class A{
public:
void func();
friend Printer& thePrinter();
private:
Printer();
Printer(const Printer* lhs);
}
Printer& thePrinter(){
static Printer p;
return p;
}
class Printer{
public:
class TooManyObject{};
Printer();
~Printer();
private:
static size_t numObject;
Printer(const Printer& rhs);
};
size_t Printer::numObject = 1;
Printer::Printer(){
if(numObject >= 1){
throw TooManyObject;
}
//其他操作
numObject++;
}
Printer::~Printer(){
//析构对象
--numObject;
}
使用类模板,通过类模板的静态变量来控制对象产生。