In addition to the point made by @Barry Schwarz about the mismatch between new and free the compiler will use its default copy constructor/copy assignment operator. Consequently, it will perform a shallow copy of the class resulting in various pointers to the allocated memory pointed to by the _string member variable. If you want your class to own the memory allocated to the _string member variable then it needs to do a deep copy -- you must write your own copy constructor/copy assignment functions for the class. Even better, include move constructor/move assignment operator also.
Simple example -
class mystring {
char* _string = nullptr;
public:
mystring()
{
}
mystring(char* newChars)
{
size_t nChars = strlen(newChars) + 1;
_string = new char[nChars];
strcpy_s(_string, nChars, newChars);
}
mystring(const mystring& rhs)
{
if (_string)
delete[] _string;
size_t nChars = strlen(rhs._string) + 1;
_string = new char[nChars];
strcpy_s(_string, nChars, rhs._string);
}
mystring(mystring&& rhs)
{
if (_string)
delete[] _string;
_string = rhs._string;
rhs._string = nullptr;
}
mystring& operator=(const mystring& rhs)
{
if (_string)
delete[] _string;
size_t nChars = strlen(rhs._string) + 1;
_string = new char[nChars];
strcpy_s(_string, nChars, rhs._string);
return *this;
}
mystring& operator=(mystring&& rhs)
{
if (_string)
delete[] _string;
_string = rhs._string;
rhs._string = nullptr;
return *this;
}
~mystring() {
if(_string)
delete [] _string;
}
operator char* () { return _string; }
};
mystring myProc2() {
mystring myString2 = "AB";
return myString2;
}
void myProc1() {
mystring myString1;
myString1 = myProc2();
}