C++ templates and header allocations -


i encountered problems memory allocations made in 1 dll (or *.so - portable code) , deallocation done in dll. errors encountered far are:

  • it doesn't work - fails assert() on debug.
  • it doesn't work if 1 dll statically linked standard c library , other dll dynamically linked it.
  • it doesn't work if 1 dll allocation dll unloaded , dll tries deallocate memory.

basically rule decided should follow not make allocations in 1 dll , release in (and preferably keep within 1 cpp file). means shouldn't allocations in header file may shared more 1 dlls. means i shouldn't allocations in tempaltes (since in header) , quite big limitation.

when need create new object in template allocate memory cpp file , run c'tor placement new operator.

// header class mybase { public:   static void* allocate(std::size_t i_size); };  template <typename t> class myclass: mybase { public:   t* createt(); };  temlpate <typename t> t* myclass<t>::createt() {   void* pmem = mybase::allocate( sizeof(t) );   return new (pmem) t; }  // cpp file void* mybase::allocate(std::size_t i_size) {   return malloc( i_size ); } 

while works, bit ugly. means writing template code without using new.

another implication if don't know template written using technique should use const methods of in header file (including other templates) (this assuming const methods don't allocate or deallocate memory). includes stl. in fact, 1 of places encountered in vector resized 1 dynamic library (on hp-ux) unloaded d'tor called dynamic library.

is there known solution i'm missing or overlooked problem?

basically rule decided should follow not make allocations in 1 dll , release in (and preferably keep within 1 cpp file). means shouldn't allocations in header file may shared more 1 dlls.

no, 1 not imply other.

if allocation , de-allocation functions templates in header, that's still fine; ensure restrict use of these functions given object 1 tu1.

encapsulate objects such invalid/prohibited/undefined code in dll 1 call these functions on objects dll 2. make contract user, write in comments ownership of objects remains original allocating context, move on next part of project without ever having worry again.

that functions available tus not relevant; after all, can always attempt delete on these things!


1 - translation unit. equivalent 1 pre-processed .cpp file.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -