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   // Note: refcount decrement and zero comparison need to happen in the same
00052   // statement for this to be thread safe.  Otherwise a race condition can
00053   // lead to multiple smart pointers deleting the memory.
00054   if (--ref_count_==0)
00055   {
00056     delete [] reinterpret_cast<char*>(data_); data_=0;
00057     delete this;
00058   }
00059 }
00060 
00061 //: Pointer to first element of data
00062 void* vil_memory_chunk::data() { return data_;}
00063 
00064 //: Pointer to first element of data
00065 void* vil_memory_chunk::const_data() const { return data_;}
00066 
00067 //: Create empty space for n elements.
00068 //  Leave existing data untouched if the size is already n.
00069 void vil_memory_chunk::set_size(unsigned long n, vil_pixel_format pixel_form)
00070 {
00071   if (size_==n) return;
00072   delete [] reinterpret_cast<char*>(data_);
00073   data_ = 0;
00074   if (n>0)
00075     data_ = new char[n];
00076   size_ = n;
00077   pixel_format_ = pixel_form;
00078 }
00079 
00080