0

I am writing an app that needs to run on both Windows and Linux. On Linux we use some custom library for heap management, and it uses placement new.

However, we dont have that library on Windows. How can we make our new logic uniform across both platforms without having to add #ifdef WINDOWS everywhere.

I was thinking of something like this:

Create a wrapper class

MyClass {
    template<T> memberVar;
}

This implementation would change for Windows vs Linux.

Windows: memberVar = new memberVar

Linux: memberVar = new(100) memberVar

In the code we would use it as follows... suppose we want to create an object of type obj1... instead of something like: obj1 objVar = new obj1() we would do: MyClass(obj1);

I am indirectly using the RAII approach here. Please comment if this would work.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Omi
  • 976
  • 2
  • 20
  • 35
  • `new (100) memberVar` wat. – Barry Jan 22 '15 at 03:17
  • 1
    Your memory management should be overriding `operator new`...you shouldn't be providing a concrete address to `placement new`. If you know that much about your underlying memory usage, you could simply use stack allocation. – Red Alert Jan 22 '15 at 03:20
  • Doug - we dont want to use placement new for Windows. we just need it for linux. – Omi Jan 22 '15 at 04:13

1 Answers1

3

You could just make a "stub" implementation of your custom heap manager which simply calls malloc() and free(). Then you can use a uniform interface with placement new on both platforms.

Alternatively, you could define your own operator new for the classes in question...this will only work if each individual class is always allocated using a specific heap manager, not some mix of the system default and the custom one. This is less flexible, but if you can live with that it's probably more readable than placement new all over the place.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436