title: Can I use reinterpret_cast to destroy non dynamically allocated objects?
body: <p>I have done a very simple implementation of vector. I admit that I have cheated a lot and the only instance variables are for example <code>size_t sz</code> and <code>T * elem</code>. The one of many problems (but this one is the only problem I know of which may cause a crash) is the problem with <code>pop_back()</code>.</p>
  
  <pre><code>template &lt;typename T&gt;
      void vec&lt;T&gt;::pop_back() {
      if (sz == 0)
          return;
      elem[sz-1].~T();
      --sz;
  }
  </code></pre>
  
  <p>The vector <code>elem</code> is a dynamically allocated array, but the objects in the array may or may not be. The problem I can see here is that this may crash in case I destroy an object in this array. This can happen in case I would destroy elements multiple times. So to say, in case I have used pop_back. This does not seem to happen for my compiler (which seems strange), but I have heard about someone having this problem with this function. I have been trying to do some research on the web and found another <a href="https://codereview.stackexchange.com/a/60502">alternative</a>. The zero check is not done here (probably laziness), and this example is using reinterpret_cast</p>
  
  <pre><code>template&lt;class T&gt;
  void Vector&lt;T&gt;::pop_back() {
  
      // You way want to do a check for empty() before calling the destructor.
  
      // Call the destructor.
      (reinterpret_cast&lt;T*&gt;(buffer)[_size-1]).~T();
  
      // It is usual to prefer the pre decrement (and pre increment).
      --_size;
  }
  </code></pre>
  
  <p>The question is, <strong>Can I really use reinterpret_cast to be able to destroy non dynamically allocated objects in my vector class?</strong></p>
  
  <p><strong>EDIT</strong></p>
  
  <p>By request I will show my push_back, which I was unsure how to properly write with the short time span I could spend on this. I admit that the main purpose of the class was not efficiency but a good way to handle resources instead of raw dynamic arrays (I can of course use a vector but this is rather a question about a smaller scope than general strategy so I would appreciate if the use-std::vector discussion was left out)</p>
  
  <pre><code>template &lt;typename T&gt;
  void vec&lt;T&gt;::push_back(const T&amp; obj) {
      T* tmp = new T[sz+1];
      if (sz &gt; 0){
          uninitialized_copy(elem, elem+sz, tmp);
          delete[] elem;
      }
      elem = tmp;
      elem[sz] = T{obj};
      ++sz;
  }
  </code></pre>
  
  <p>The main problem was the capacity. I realized the capacity part would require a lot of work and without that I could just create new elements.</p>