Reputation: 1148
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.
Upvotes: 0
Views: 98
Reputation: 249133
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.
Upvotes: 3