ACE_Message_Block
ACE_Message_Block用于构建“固定”和“可变”长度的消息。ACE_Message_Block可以将多条消息连接在一起,形成一个链表,从而支持复合消息。ACE_Message_Block内部结构图如下:
头文件“Message_Block.h”。
1:ACE_Message_Block初始化与释放
初始化一般用以下操作实现:
ACE_NEW_NORETURN (m_pRcvmb,ACE_Message_Block (1024)); ACE_Message_Block* p = new ACE_Message_Block(1024);
这两种方式都可以实现ACE_Message_Block的new操作。ACE定义了一组申请内存的宏,内部都实现了new操作符。这组宏定义在如下:
# if defined (ACE_HAS_NEW_NOTHROW) # define ACE_NEW_RETURN(POINTER,CONSTRUCTOR,RET_VAL) do { POINTER = new (ACE_nothrow) CONSTRUCTOR; if (POINTER == 0) { errno = ENOMEM; return RET_VAL; } } while (0) # define ACE_NEW(POINTER,CONSTRUCTOR) do { POINTER = new(ACE_nothrow) CONSTRUCTOR; if (POINTER == 0) { errno = ENOMEM; return; } } while (0) # define ACE_NEW_NORETURN(POINTER,CONSTRUCTOR) do { POINTER = new(ACE_nothrow) CONSTRUCTOR; if (POINTER == 0) { errno = ENOMEM; } } while (0) # else # define ACE_NEW_RETURN(POINTER,CONSTRUCTOR,RET_VAL) do { try { POINTER = new CONSTRUCTOR; } catch (ACE_bad_alloc) { ACE_del_bad_alloc errno = ENOMEM; POINTER = 0; return RET_VAL; } } while (0) # define ACE_NEW(POINTER,CONSTRUCTOR) do { try { POINTER = new CONSTRUCTOR; } catch (ACE_bad_alloc) { ACE_del_bad_alloc errno = ENOMEM; POINTER = 0; return; } } while (0) # define ACE_NEW_NORETURN(POINTER,CONSTRUCTOR) do { try { POINTER = new CONSTRUCTOR; } catch (ACE_bad_alloc) { ACE_del_bad_alloc errno = ENOMEM; POINTER = 0; } } while (0) # endif /* ACE_HAS_NEW_NOTHROW */
值得注意的是,ACE_Message_Block有多个构造函数,最常用的一个构造函数定义为:
ACE_Message_Block (size_t size, ACE_Message_Type type = MB_DATA, ACE_Message_Block *cont = 0, const char *data = 0, ACE_Allocator *allocator_strategy = 0, ACE_Lock *locking_strategy = 0, unsigned long priority = ACE_DEFAULT_MESSAGE_BLOCK_PRIORITY, const ACE_Time_Value &execution_time = ACE_Time_Value::zero, const ACE_Time_Value &deadline_time = ACE_Time_Value::max_time, ACE_Allocator *data_block_allocator = 0, ACE_Allocator *message_block_allocator = 0);
在该构造函数内部,ACE_Message_Block调用了init_i函数,init_i内部调用了ACE_Data_Block的构造函数。ACE_Data_Block定义了一个char* base_ 指针,其构造函数会调用C风格的malloc方法为base_申请大小为size的空间。也就是说,ACE_Message_Block真正的数据载体是ACE_Data_Block。其实现代码为:
//ACE_Message_Block内部申请ACE_Data_Block的空间 ACE_NEW_MALLOC_RETURN (db,static_cast<ACE_Data_Block *> (data_block_allocator->malloc (sizeof (ACE_Data_Block))), ACE_Data_Block (size, msg_type, msg_data, allocator_strategy, locking_strategy, flags, data_block_allocator),-1); //ACE_Data_Block内部为base_申请大小为size的空间 if (msg_data == 0) { ACE_ALLOCATOR (this->base_,(char *) this->allocator_strategy_->malloc (size)); #if defined (ACE_INITIALIZE_MEMORY_BEFORE_USE) (void) ACE_OS::memset (this->base_,'