Memory manager and class constructors!

Started by
4 comments, last by Washu 19 years, 6 months ago
Hello! i want to create a realy simple memory manager. simply just a wrapper for new and delete with some ekstra stuff... (logging, garbage...) Now this is my problem: if i write: MyClass *class = new MyClass(); delete class; both the constructor and destructor of MyClass will be called... if i instead write: MyClass *class = MyNew(size); where MyNew only returns a pointer to some free mem i allocated at startup, the constructor will not be called... how could i solve this? (without advanced templates... an ekstra variable is ok...) -anders
-Anders-Oredsson-Norway-
Advertisement
Quote:Original post by uncutno
constructor will not be called... how could i solve this?
(without advanced templates... an ekstra variable is ok...)


you can use placement new to initialize uninitialized memory e.g.

#include <new>/*....*/MyClass *class = MyNew(size);class = new(class) Myclass;


you need to include header new.
Which should also be followed by an explicit call to its destructor

class->~MyClass();
Quote:Original post by elementary
Which should also be followed by an explicit call to its destructor

class->~MyClass();


and then deallocate the memory, if you wont to get picky about it [smile]
thanks!!

Is there a way do do this inside MyNew and MyDelete? Calling the constructor without the class definition? (sound like it should be illegal)

can this be solved with a templated function in a class? it should be possible, but is this the right way to do it?

im thinking about a mem manager where all memory is allocated at start, and deleted at the end... will fitt perfectly with my sort of paging world data mem system...
-Anders-Oredsson-Norway-
With templates, yes.
template<typename T>T* MyNew(std::size_t size) {  //allocate  new (mem) T();}


roughly the same idea with MyDelete.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

This topic is closed to new replies.

Advertisement