title: C++ implicit class to char* conversion
body: <p>I'm doing an exercise right now, so I will say right away that I don't want to use std::string to solve my problem.</p>
  
  <p>I have a simple class that has a few fields and among them is char* text field that can be assigned and re-written or re-allocated.</p>
  
  <pre><code>class MyClass
  {
  private:
    char* name;
  ...
  public:
    operator char*() const { return name;}
  }
  </code></pre>
  
  <p>What I'm trying to do is make an implicit conversion to char* so that I can do this in my program:</p>
  
  <pre><code>Myclass s = "Hello"    //allocates 6 bytes and pust a 0-terminated "Hello/0" line into "name"
  
  char* c = s
  
  s = "Hello World"      //re-allocates memory, frees previous memory
  
  cout &lt;&lt; "Str: " &lt;&lt; s &lt;&lt; " Char: " &lt;&lt; c;
  </code></pre>
  
  <p>Obviously, just as I noticed even before testing, when the re-allocation of "name" happens and the memory is freed - "c" now points to garbage.
  So this code is no-go and I fully understand why.</p>
  
  <p>I could allocate new memory and return a pointer to it, I guess:</p>
  
  <pre><code>operator char*() const
  {
    int length = strlen(name)+1;
    char* ptr = new char[length]
    std::copy(name, name+length, ptr);
    return ptr;
  }
  </code></pre>
  
  <p>but in this case, if I later re-assign "c" to something else - then the memory will never be freed, right? If I do this:</p>
  
  <pre><code>c = "Bye";
  </code></pre>
  
  <p>then basically the memory that I copied "name" to will still remain allocated and leaK?</p>
  
  <p>The question is: how to make this right? Should I even worry about this, or do I simply assume that the user who re-assigns "c" should take care of clearing the memory first?</p>
  
  <p>I will repeat that my goal is to do this through memory manipulation and pointers rather than safely use std::string.
  Thank you!</p>