0

Starting in myProc1(). I found that myProc2() operates

on separate Variable on stack than myString1. After there is operator=

which has to have CONST parameter.

Following app breaks up because setting other string to NULL is not possible.

How to make it working?

class string {
public:
    char* _string;
    string() {    }
    string(char* newChars) {
        _string = newChars;
    }
    ~string() {
        delete _string;
    }
    string(string& other) {//made for return declaration
        _string = other._string;
        other._string = NULL;
    }
    string& operator=(const string& other) {
        if (this == &other)
            return *this;
        _string = other._string;
     //   other._string = NULL;//NOT WORKING, HAD TO BE CONST
        return *this;
    }
};


string myProc2() {
    string myString2 = new char[] {'A','B',0};
    return myString2;
}

void myProc1() {
    string myString1;
    myString1 = myProc2();
}
  • 1
    You need to implement a copy constructor and assignment operator. You should also use `delete` with `new`, `free` is for things you have used `malloc` on – Alan Birtles Nov 21 '20 at 08:40
  • 1
    You can take this to three different paths: reference counting (e.g. `std::shared_ptr`), move-only (e.g. `std::unique_ptr`) or deep copy (e.g. `std::string`). If you just use a copy constructor for the pointer, you'll either use after free or leak memory. – Joel Filho Nov 21 '20 at 08:42

0 Answers0