Macro to ease auto_ptr usage


/ Published in: C++
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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.

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.