C++笔记 04:避免无用的缺省构造函数

本文介绍了在C++编程中避免使用默认构造函数的原因,包括在非堆数组、模板容器及虚基类设计中的问题。通过示例展示了使用非堆数组、指针数组和定位new来替代默认构造函数的方法,讨论了这些方法在内存管理和效率上的考量。
摘要由CSDN通过智能技术生成

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 设计虚基类所面临的要提供缺省构造函数还是不提供缺省构造函数的两难政策

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值