core/vil/vil_memory_chunk.cxx
Go to the documentation of this file.
00001 // This is core/vil/vil_memory_chunk.cxx
00002 #include "vil_memory_chunk.h"
00003 //:
00004 // \file
00005 // \brief Ref. counted block of data on the heap
00006 // \author Tim Cootes
00007 #include <vcl_cstring.h>
00008 #include <vcl_cassert.h>
00009 
00010 //: Dflt ctor
00011 vil_memory_chunk::vil_memory_chunk()
00012 : data_(0), size_(0), pixel_format_(VIL_PIXEL_FORMAT_UNKNOWN), ref_count_(0)
00013 {
00014 }
00015 
00016 //: Allocate n bytes of memory
00017 vil_memory_chunk::vil_memory_chunk(vcl_size_t n, vil_pixel_format pixel_form)
00018 : data_(new char[n]), size_(n), pixel_format_(pixel_form), ref_count_(0)
00019 {
00020   assert(vil_pixel_format_num_components(pixel_form)==1
00021     || pixel_form==VIL_PIXEL_FORMAT_UNKNOWN );
00022 }
00023 
00024 //: Destructor
00025 vil_memory_chunk::~vil_memory_chunk()
00026 {
00027   delete [] reinterpret_cast<char*>(data_);
00028 }
00029 
00030 //: Copy ctor
00031 vil_memory_chunk::vil_memory_chunk(const vil_memory_chunk& d)
00032 : data_(new char[d.size()]), size_(d.size()), pixel_format_(d.pixel_format_), ref_count_(0)
00033 {
00034   vcl_memcpy(data_,d.data_,size_);
00035 }
00036 
00037 //: Assignment operator
00038 vil_memory_chunk& vil_memory_chunk::operator=(const vil_memory_chunk& d)
00039 {
00040   if (this==&d) return *this;
00041 
00042   set_size(d.size(),d.pixel_format());
00043   vcl_memcpy(data_,d.data_,size_);
00044   return *this;
00045 }
00046 
00047 //: Decrement reference count and call destructor when it becomes zero
00048 void vil_memory_chunk::unref()
00049 {
00050   assert (ref_count_ >0);
00051   --ref_count_;
00052   if (ref_count_==0)
00053   {
00054     delete [] reinterpret_cast<char*>(data_); data_=0;
00055     delete this;
00056   }
00057 }
00058 
00059 //: Create empty space for n elements.
00060 //  Leave existing data untouched if the size is already n.
00061 void vil_memory_chunk::set_size(unsigned long n, vil_pixel_format pixel_form)
00062 {
00063   if (size_==n) return;
00064   delete [] reinterpret_cast<char*>(data_);
00065   data_ = 0;
00066   if (n>0)
00067     data_ = new char[n];
00068   size_ = n;
00069   pixel_format_ = pixel_form;
00070 }
00071 
00072