title: C++ strings - How to avoid obtaining invalid pointer?
body: <p>In our C++ code, we have our own string class (for legacy reasons). It supports a method <code>c_str()</code> much like <code>std::string</code>. What I noticed is that many developers are using it incorrectly. I have reduced the problem to the following line:</p>
  
  <pre><code> const char* x = std::string("abc").c_str();
  </code></pre>
  
  <p>This seemingly innocent code is quite dangerous in the sense that the destructor on <code>std::string</code> gets invoked immediately after the call to <code>c_str()</code>. As a result, you are holding a pointer to a de-allocated memory location.</p>
  
  <p>Here is another example:</p>
  
  <pre><code>  std::string x("abc");
    const char* y = x.substr(0,1).c_str();
  </code></pre>
  
  <p>Here too, we are using a pointer to de-allocated location.</p>
  
  <p>These problems are not easy to find during testing as the memory location still contains valid data (although the memory location itself is invalid).</p>
  
  <p>I am wondering if you have any suggestions on how I can modify class/method definition such that developers can never make such a mistake.</p>