[ create a new paste ] login | about

Link: http://codepad.org/TcCPHRjf    [ raw code | output | fork ]

AaronMiller - C++, pasted on May 20:
#include <cstdio>
#include <cstddef>
#include <cstdlib>
#include <cstring>

//
// NOTE: None of the following is expected to work.
//

// is it possible to have a return-type template function?
template<typename T> T *New() {
  T *p;

  p = (T *)malloc(sizeof(T));
  if (!p) exit(EXIT_FAILURE);

  new(p) T();

  return p;
}

// invoke the destructor manually?
template<typename T> T *Delete(T *p) {
  if (!p)
    return (T *)0;

  p->~T(); //invoke destructor manually like this?

  free((void *)p); //this isn't a double free
  return (T *)0;
}

// let's find out!
int main() {
  int *p;

  p = New<int>();
  *p = 42;
  printf("%i\n", *p);
  Delete(p);

  return EXIT_SUCCESS;
}


Output:
1
42


Create a new paste based on this one


Comments: