c++ - 我应该返回对堆对象的引用还是返回值?

标签 c++ performance memory-management reference

我有这两个简单的功能。我认为 func1 是一个很好的解决方案,因为您可以通过引用传递对象。我的教科书给出了 func2 作为最佳解决方案的答案。这仅仅是因为您没有解除分配 heapstr 吗?如果我在 main 中声明 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;
}

最佳答案

Should I return reference to heap object or return value?

按值返回。

有很多原因,但没有一个真正与性能相关,因为编译器在优化事物方面足够好,即使不是,大多数程序都是 I/O-bound,即你的时间等待来自文件或网络套接字的数据会耗尽您的所有性能,而不是 CPU 操作本身所花费的时间。

例如,参见 Herb Sutter 和 Bjarne Stroustrup 的“C++ 核心指南”,在 "Return containers by value (relying on move or copy elision for efficiency)" 节中说:

Reason

To simplify code and eliminate a need for explicit memory management.

至于你的两个函数...

My textbook gave func2 as the answer for the best solution. Is this only because you aren't deallocateing heapstr?

内存泄漏是问题之一。但重点很简单,按值返回更简单,更不容易出错。一切都是为了正确性,而不是速度。如果您可以只返回一个 int,您就不会返回一个 int*,对吗?

What if I declared heapstr in main and then passed it to the function so I was able to delete it afterwards?

您会在代码中引入很多内存泄漏、崩溃和未定义行为的可能性。它会变得更长、更难编写、更难阅读、更难维护、更难调试以及更难在代码审查中证明其合理性。作为返回,您将一无所获。

关于c++ - 我应该返回对堆对象的引用还是返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47737630/

相关文章:

c++ - 3维数组的重新分配

objective-c - 我可以自动释放 NSProxy 实例吗?

具有内存错误访问的 C++ struct new

c++ - 将#include 包装在命名空间 block 中是个好主意吗?

java - Java EE 应用程序中的并发

c++ - 写入指定内存位置

c# - 为这个问题选择正确的数据结构 : circular linked list, 列表、数组或其他

sql - 将数据存储为数字和 double

c++ - lineEdit的QT设置文本

c++ - 为什么这是常量字符,而不是普通字符?