读书笔记:Effective C++ 2.0 版,条款6(析构时delete)、7(内存不足)

条款6: 析构函数里对指针成员调用delete

指针管理,应该明确其生存周期、new delete mana策略。

在构造函数中new,在析构函数中delete,是一种简单可行的方案。虽然并不是适用于所有情况,有基本规则总是好的。

写过一个内存管理的代码,需要支持内存数据的递归式联动,外加撤消重做(撤销重做后依然支持内存数据的递归联动)。从实践来看,在有限可控的函数中执行new delete,配合set、map,实际是比较容易实现内存的垃圾回收机制的。

减少new、delete的使用,更应该被提倡。尽量用函数局部栈内对象,可以避免new、delete的内存管理,减少内存碎片,提高效率、稳定性。

另外,重新强调c的malloc、free是没有构造析构的,可控性更好。

条款7: 预先准备好内存不够的情况

c风格

c 复制代码
typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();
// function to call if operator new can't allocate enough memory
void nomorememory(){
	cerr << "unable to satisfy request for memory\n";
	abort();
}
int main(){
	set_new_handler(nomorememory);
	int *pbigdataarray = new int[100000000];
	...	
}

cpp模板风格

c 复制代码
template<class t>	// 提供类set_new_handler支持的
class newhandlersupport {	// 混合风格"的基类
public:
	static new_handler set_new_handler(new_handler p);
	static void * operator new(size_t size);
private:
	static new_handler currenthandler;
};
template<class t>
new_handler newhandlersupport<t>::set_new_handler(new_handler p){
	new_handler oldhandler = currenthandler;
	currenthandler = p;
	return oldhandler;
}
template<class t>
void * newhandlersupport<t>::operator new(size_t size){
	new_handler globalhandler = std::set_new_handler(currenthandler);
	void *memory;
	try {
		memory = ::operator new(size);
	}
	catch (std::bad_alloc&) {
		std::set_new_handler(globalhandler);
		throw;
	}	
	std::set_new_handler(globalhandler);
	return memory;
}
// this sets each currenthandler to 0
template<class t>
new_handler newhandlersupport<t>::currenthandler;
// note inheritance from mixin base class template. (see
// my article on counting objects for information on why
// private inheritance might be preferable here.)
class x: public newhandlersupport<x> {
...		// as before, but no declarations for
};		// set_new_handler or operator new

书中认为:使用set_new_handler是处理内存不够情况下一种方便、简单的方法。这比把每个new都包装在try模块里当然好多了。

我个人都没有使用,常用的方法是在main中写一个try catch兜底,输出标准异常的信息即可。

另外就是,可以考虑,32位程序在new之前进行内存可用值的判断。过多内存的情况下,内存实际可以new出来,但会触发许系统的内存回收和整理?win下有长时间卡顿情况。

64位程序基本就不太需要考虑这个了。

64位程序需要考虑的是内存消耗过大,导致的效率问题,需要考虑实时动态预警和自动处理。

相关推荐
樱木Plus20 小时前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit3 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_4 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星4 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛6 天前
delete又未完全delete
c++
端平入洛7 天前
auto有时不auto
c++
哇哈哈20218 天前
信号量和信号
linux·c++
多恩Stone8 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马8 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝8 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode