c++ 函数中的按值返回

发布于 2024-10-11 10:58:23 字数 228 浏览 6 评论 0原文

这段代码在 C++ 中正确吗?

list<int> makelist(int litem)
{
    list<int> newList;
    newList.push_front(litem);
    return newList;
}

按值返回列表(#include)是否会出现问题?

is this code correct in c++?

list<int> makelist(int litem)
{
    list<int> newList;
    newList.push_front(litem);
    return newList;
}

should it make problems to return a list (of #include <list>) by value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深海不蓝 2024-10-18 10:58:23

正如所评论的,按值返回通常会被优化掉(当打开优化运行时)。因此,如果速度是问题所在(在分析器证明之前不应该如此),您不必担心。另一方面,如果列表在复制时有一些奇怪的副作用,您应该意识到复制构造函数调用的数量将根据编译器和设置而变化。

As commented, returning by values will normally be optimized away (when running with optimization turned on). So if speed is the concern (which it shouldn't until it has been proven by a profiler) you shouldn't worry. If list on the other hand has some strange side effects when copying you should be aware of the number of copy constructor calls will vary depending on compiler and settings.

无可置疑 2024-10-18 10:58:23

它会起作用,但效率不高,因为可能会复制大量内存。在下一个C++标准中,这个问题可以得到解决。
我建议使用以下代码:

void fillList(list & lst) {
   lst.push_front(...);
}
....
list newList;
fillList(newList);

It'll work, but it's not efficient, because a lot of memory might be copied. In the next C++ standard, this problem can be solved.
I'd suggest the following code:

void fillList(list & lst) {
   lst.push_front(...);
}
....
list newList;
fillList(newList);
愛上了 2024-10-18 10:58:23

您不能返回非简单类型(int、float、char)的本地对象,但您可以返回指向新对象的指针:

list<int>* makelist(int litem)
{
    list<int>* newList = new list<int>();
    newList->push_front(litem);
    return newList;
}

请注意,您必须管理后者的指针以避免内存泄漏。

You can't return a local object that aren't a simply type (int, float, char), but you can return a pointer to a new object:

list<int>* makelist(int litem)
{
    list<int>* newList = new list<int>();
    newList->push_front(litem);
    return newList;
}

take care that you MUST manage the pointer latter to avoid memory leaks.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文