Jump to content
  • Advertisement
Sign in to follow this  
Alundra

Template or Macro

This topic is 1336 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,

Is it better to have a template or macro and why ?

Example of one macro which could be a template :

#define SAFE_DELETE( p ) { delete p; p = NULL; }

Thanks

Share this post


Link to post
Share on other sites
Advertisement

There are a few templates in the standard library for safe delete already: here, here and here, for example. So the standard apparently thought it was better to use templates in this case at least.

Edited by Brother Bob

Share this post


Link to post
Share on other sites
I think you should prefer templates unless you have a good reason not to.

If you pass an array to SAFE_DELETE it will still compile, but using templates you can force this to give you an error.

int arr[5];
SAFE_DELETE(arr);

Share this post


Link to post
Share on other sites

My rule of thumb is to restrict the use of macros constructs that are not related to ordinary c++ code. First example is conditional compilation, i.e. to include or exclude some portions of code that target specific platforms. Another example is assertions, which can't be considered normal code that is supposed to be part of the execution. A third example could be error logging (but that could depend on the context). I'm also using some macros to define and embed shader code inside c++ code.

 

So in your example, pointer deletion *is* normal code and should *not* use macros. Read up on std::unique_ptr and std::shared_ptr and you'll see that those templates work way better anyway.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!