Having such simple program:
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
extern char MsgBuff[300];
class MyStr {
string* strPtr;
public:
// "normal" constructor
MyStr(const string& strPtr) : strPtr(new string(strPtr)) {}
// destructor
~MyStr() {
if(strPtr != NULL)
delete strPtr;
}
// copy constructor
MyStr(const MyStr& x) : strPtr(x.strPtr) {
OutputDebugStringA("copy constructor");
}
// move constructor
MyStr(MyStr&& x) : strPtr(x.strPtr) {
x.strPtr = nullptr;
OutputDebugStringA("copy constructor");
}
};
int main() {
MyStr foo("Exam");
MyStr foo2 = foo;
return 0;
}
The program throws an exception: Exception thrown: read access violation.
As i invesigated it's caused by the destructor
code - destroying these two objects (foo, foo2) we are freeing TWICE the same memory pointed by strPtr
pointer.
How can this code be fixed to preserve the logic and avoid the exception?