Posted By

jarnaldich on 12/12/08


Tagged

memory


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

khouser


Macro to ease auto_ptr usage


 / Published in: C++
 

URL: http://www.cppreference.com/wiki/stl/memory/auto_ptr

Use this macro to help declaring auto-release pointers in C++. See usage in the source. Remember that std::auto_ptr is a standard template class that helps releasing memory, since the pointer you provide in the constructor will be released in the destructor of the class. This means that memory is released "automagically" when the variable goes out of scope. Use of this class is specially advisable in a method with serveral returns or capable of throwing an exception.

  1. #include <memory> // to use auto_ptr
  2.  
  3. // Macro: N stands for Name, L for Lenght and T for Type
  4. #define AUTO_PTR(N, L, T) T* p##N = new T[L]; std::auto_ptr<T> auto_##N(p##N);
  5.  
  6. // Sample usage
  7. AUTO_PTR(cFileName, MAX_PATH, char);
  8. gets(pcFileName); // Pointer can be accessed with "p" as a prefix.

Report this snippet  

You need to login to post a comment.