I have these two simple functions. I thought that func1
was a good solution since you pass an object by reference. My textbook gave func2
as the answer for the best solution. Is this only because you aren't deallocateing heapstr
? What if I declared heapstr
in main and then passed it to the function so I was able to delete it afterwards?
#include <iostream>
using namespace std;
string& func1(const string &str) {
string* heapstr=new string();
for (int i = 0; i < str.size(); ++i) {
*heapstr += str[i];
}
return *heapstr;
}
string func2(const string &str) {
string heapstr;
for (int i = 0; i < str.size(); ++i) {
heapstr += str[i];
}
return heapstr;
}
int main() {
cout << func1("aaa") << endl;
cout << func2("aaa") << endl;
}