Quick and dirty C++ managed memory
-
Why not have the "new" operator return a typed handle when you get memory on the heap (if you want it to)? And then use a "lock" operator to get a pointer to the memory, and the pointer is only valid within the scope of the function. Then on idle time, all memory is unlocked and can be compacted. I wonder if there is a way of doing this by overiding the global new and delete operators and somehow checking for handle types? In any case I think it would be better if the compiler was in on the action. For instance you could declare a handle: char* # hString; hString = new char[80]; char* pString = lock hString; strcpy( pString, "A String"); int len = strlen( pString ); And when you want to free the memory: delete [] hString; And when calling a member function: CThisObject* # hThis = new CThisObject( data ); if( hThis ) hThis->DoThat(); is the same as: CThisObject* # hThis = new CThisObject( data ); if( hThis ) { CThisObject* p = lock hThis; p->DoThat(); } In any case, I'm sure die-hard C++ programmers would prefer managed memory along these lines instead of all the crap you have to deal with in .NET managed C++.