typedef struct __String { char* data; // C-string data, unsigned* copyRef; // number of copy reference, // delete only when the copyRef is 0 bool isACopy; // this boolean is true when *data // is a ref to an other MyString __String () { data = 0; isACopy = false; copyRef = new unsigned; *copyRef = 0; return; } void addCopyRef() { *copyRef++; } void removeCopyRef() { *copyRef--; } } *MyString; void Initialize(MyString& string){ string->data = new char[100]; string->data[0] ='\0'; // this generate an error! string->copyRef = new unsigned(); string->addCopyRef(); } int main() { MyString mystring = new struct __String; Initialize(mystring); }
I tested it without errors. from g ++ to linux. I think you are better
- at least provide an error message here
- and your compiler and the platform you are working on.
I checked again with another main () below.
int main() { MyString mystring = new struct __String; MyString mystring1 = new struct __String; MyString mystring2 = new struct __String; Initialize(mystring); Initialize(mystring1); Initialize(mystring2); }
There is no error using this test code. I think you skipped creating the object pointed to by mystring (In your code, left_string , right_string , both_string ). This will probably be the reason.
And this code creates a memory leak from the constructor. In this state of code, a constructor is not needed.
source share