More Effective C++笔记
1 避免无用的缺省构造函数
1.1 数组无法使用
1.使用非堆数组(non-heap arrays)
2.使用指针数组来代替一个对象数组
3.定位new(placement new)
#include <iostream>
using namespace std;
class EquipmentPiece
{
public:
EquipmentPiece(int id) {};
};
void test01()
{
//使用非堆数组
EquipmentPiece bestPieces[] =
{
EquipmentPiece(1),
EquipmentPiece(2),
EquipmentPiece(3)
};
}
void test02()
{
//使用一个指针数组来代替一个对象数组
typedef EquipmentPiece* PEP;
//PEP bestPieces[10];
PEP *bestPieces = new PEP[10];
for (int i = 0; i < 3; ++i)
bestPieces[i] = new EquipmentPiece(i);
for (int i = 0; i < 3; ++i)
delete bestPieces[i];
}
void test03()
{
//定位new(placement new)
void *rawMemory = operator new[](3 * sizeof(EquipmentPiece));
EquipmentPiece *bestPieces = static_cast<EquipmentPiece*>(rawMemory);
for (int i = 0; i < 3; ++i)
new(&bestPieces[i]) EquipmentPiece(i);
for (int i = 2; i >= 0; --i)
bestPieces[i].~EquipmentPiece();
operator delete[](rawMemory);
}
int main()
{
#if 0
//不存在默认构造函数,无法编译
EquipmentPiece bestPieces[10];
EquipmentPiece *bestPieces = new EquipmentPiece[10];
#endif // 0
test01();
test02();
test03();
return 0;
}
1.2 无法在许多基于模板(template-based)的容器类里使用
1.3 设计虚基类所面临的要提供缺省构造函数还是不提供缺省构造函数的两难政策