나는이 두 가지 간단한 기능을 가지고 있습니다. 나는 func1
이 객체를 참조로 전달 했으므로 좋은 해결책이라고 생각했습니다. 내 교과서는 최상의 솔루션에 대한 답변으로 func2
을 부여했습니다. 이것은 heapstr
의 할당을 해제하지 않았기 때문입니까? 주에서 heapstr
을 선언하고 함수에 전달하면 나중에 삭제할 수 있습니까? 이 교과서 예제이기 때문에힙 객체 또는 반환 값에 대한 참조를 반환해야합니까?
#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;
}
가치! 항상 기본값으로 값을 선호합니다! 그 누출에 대해서 이야기조차하지 않고 있습니다. – StoryTeller
'func2', 더 안전하고 빠름 (https://stackoverflow.com/questions/161053/which-is-faster-stack-allocation-or-heap-allocation) – macroland
일반 포인터를 사용하려면 다시 생각해보십시오. 그렇게할만한 이유가 있다면 – Simon