I crashed application every time I ran the code below. During debugging, I saw that the str
object was self-destructing itself after the second line in main()
. And it's quite a mystery for me. Try run it yourself:
#include<iostream>
class String {
private:
char* string = nullptr;
int length = 0;
public:
String(const char str[]) {
for (length; str[length] != '\0'; ++length);
string = new char[length + 1]{};
for (int i{}; i < length; ++i)
string[i] = str[i];
string[length] = '\0';
}
~String() {
delete[] string;
}
auto print() {
for (int i{}; i < length; ++i)
std::cout << string[i];
std::cout << '\n';
return *this;
}
auto getStrPtr() {
return string;
}
};
int main() {
String str("123");
auto strPtr{ str.print().getStrPtr() };
strPtr[0] = '3';
}
Am I missing something?
Note on line 2 in main()
: I am trying to print the str
's string
array and then, since print()
returns *this
, I can chain methods and am calling a function that returns string
's pointer. But, even if in debugger it all executes perfectly, I have no idea why the hell str
object deconstructs itself after.