here is mystr struct
#include <stdio.h>
#include <string.h>
struct mystr {
char *str;
mystr(const char *s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
printf("[1]%s\n", s);
}
mystr(const mystr &s) {
str = new char[strlen(s.str) + 1];
strcpy(str, s.str);
}
~mystr() {
delete[] str;
}
void printn() const {
printf("%s\n", str);
}
//mystr& operator+=(const char *s) this line works!
mystr operator+=(const char *s) {
char *old = str;
int len = strlen(str) + strlen(s);
str = new char[len + 1];
strcpy(str, old);
strcat(str, s);
printf("[2]%s,%s,%s\n", old, s, str);
delete[] old;
return *this;
}
};
here is main code
int main() {
mystr s = "abc";
(s += "def") += "ghi";
// only print s = abcdef
// when put & before operator+=, it prints s = abcdefghi
printf("s = %s\n", s.str);
}
Question
What is difference between return mystr & vs mystr? I see operator+= is called twice, but output is different. in c++ what behavior in return instance?