Reputation: 75
I follow some common DirectX tutorial on the web which features classes and structuring. I need to allocate memory for XMVECTOR and XMMATRIX because of the specific memory allocation issue.
Now it all works, but I wish to make teh code cleaner. Question is: Is there a way to override new and delete for those structures(so the malloc and pointer conversion details are hidden by the word "new", similarly with the delete) and if so how?
Edit 2014-07-11:
The comments so far suggested two way to workaround the problem by:
1) using a wrapper class for the structures and overloading/overriding delete and new for the wrapper class.
The problem with this is the obvious performance hit and the need to access member structure ever single time (less cleaner code, which defeats the whole purpose).
2) Using XMFLOAT4 and similar structures.
Problem with this is that this makes it easier with memory allocation but adds complications in conversions between types (as XMMATRIX and XMVECTOR are the ones returned by DirectXMath functions). Those conversions also make the code less cleaner so it's like replacing a pile of dog poop with cat poop, it's still poop in the end (yeah, the best comparison I could come up with to convey meaning).
Upvotes: 0
Views: 325
Reputation: 41057
The general recommendation is to use the various memory structures (XMFLOAT4, etc.) and Load/Stores. If you were targeting only x64 native, you could use XMVECTOR/XMMATRIX directly since that platform uses 16-byte aligned memory by default.
The overloading new/delete recommendation is not for XMVECTOR or XMMATRIX. Rather you can overload new/delete for your classes that contain these types to use __aligned_malloc( x, 16 ). Global overriding of new/delete is possible, but doing it per-class is actually the recommended solution. See the Scott Meyers "Effective C++" books for detailed discussion of overriding new/delete.
Another approach is to use the pImpl idiom like the DirectX Tool Kit does. The public class is unaligned but the internal class uses __aligned_malloc( x, 16 ). This actually works really well, and both the implementation and the client code doesn't end up looking like "poop".
Finally, you could make use of the SimpleMath wrapper in the DirectX Tool Kit which provides classes that derive from XMFLOAT4, etc. with implicit conversions. It is not as efficient, but it does look clean without worrying about the alignment issues.
BTW, this topic is covered in the DirectXMath Programmer's Guide on MSDN.
Upvotes: 2