// 重载赋值操作符 smart_ptr& operator= (const smart_ptr& rhs) { //给自身赋值也对,因为如果自身赋值,计数器先减1,再加1,并未发生改变 ++*count; decr_count(); pointee = rhs.pointee; count = rhs.count; return *this; }
bool msgpack_unpacker_expand_buffer(msgpack_unpacker* mpac, size_t size) { if(mpac->used == mpac->off && get_count(mpac->buffer) == 1 && !CTX_REFERENCED(mpac)) { // rewind buffer mpac->free += mpac->used - COUNTER_SIZE; mpac->used = COUNTER_SIZE; mpac->off = COUNTER_SIZE; if(mpac->free >= size) { return true; } } if(mpac->off == COUNTER_SIZE) { char* tmp; size_t next_size = (mpac->used + mpac->free) * 2; // include COUNTER_SIZE while(next_size < size + mpac->used) { size_t tmp_next_size = next_size * 2; if (tmp_next_size <= next_size) { next_size = size + mpac->used; break; } next_size = tmp_next_size; } tmp = (char*)realloc(mpac->buffer, next_size); if(tmp == NULL) { return false; } mpac->buffer = tmp; mpac->free = next_size - mpac->used; } else { char* tmp; size_t next_size = mpac->initial_buffer_size; // include COUNTER_SIZE size_t not_parsed = mpac->used - mpac->off; while(next_size < size + not_parsed + COUNTER_SIZE) { size_t tmp_next_size = next_size * 2; if (tmp_next_size <= next_size) { next_size = size + not_parsed + COUNTER_SIZE; break; } next_size = tmp_next_size; } tmp = (char*)malloc(next_size); if(tmp == NULL) { return false; } init_count(tmp); memcpy(tmp+COUNTER_SIZE, mpac->buffer+mpac->off, not_parsed); if(CTX_REFERENCED(mpac)) { if(!msgpack_zone_push_finalizer(mpac->z, decr_count, mpac->buffer)) { free(tmp); return false; } CTX_REFERENCED(mpac) = false; } else { decr_count(mpac->buffer); } mpac->buffer = tmp; mpac->used = not_parsed + COUNTER_SIZE; mpac->free = next_size - mpac->used; mpac->off = COUNTER_SIZE; } return true; }
void msgpack_unpacker_destroy(msgpack_unpacker* mpac) { msgpack_zone_free(mpac->z); free(mpac->ctx); decr_count(mpac->buffer); }
// 析构,计数减1,减到0时进行垃圾回收,即释放空间 ~smart_ptr() { decr_count(); }