201-C++construct

本文深入探讨了C++中的构造函数和析构函数,包括如何使用模板实现构造和析构,以及如何进行对象的初始化和销毁。`construct`和`destroy`函数模板展示了如何为对象分配和释放内存,特别是对于具有复杂初始化和析构过程的对象。此外,还详细解释了`__destroy`辅助函数,用于处理容器中对象的析构操作,确保正确地调用每个对象的析构函数。
摘要由CSDN通过智能技术生成
#ifndef YHP_CONSTRUCT_H
#define YHP_CONSTRUCT_H
#include"yhp_iterator.h"
#include"yhp_type_traits.h"
namespace yhp
{
template<class T1,class T2>
inline void construct(T1 *p,const T2 &val)
{
	new(p) T1(val);
}
template<class T>
inline void construct(T *p)
{
	new(p)  T();
}

template<class T>
inline void destroy(T *p)
{
	p->~T();
}

template<class _FI>
inline void destroy(_FI _F, _FI _L)
{
	__destroy(_F,_L,value_type(_F));
}
template<class _FI,class T>
inline void __destroy(_FI _F,_FI _L , T *)
{
	__type_traits<T>();
	typedef typename __type_traits<T>::has_trivial_destructor  dest;
	__destroy_aux(_F,_L,dest());
}
template<class _FI>
inline void __destroy_aux(_FI _F,_FI _L , __true_type)
{}

template<class _FI>
inline void __destroy_aux(_FI _F,_FI _L , __false_type)
{
	for(; _F != _L; ++_F)
	{
		destroy(&*_F);
	}
}
}
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值