c++ 函数中的按值返回
这段代码在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如所评论的,按值返回通常会被优化掉(当打开优化运行时)。因此,如果速度是问题所在(在分析器证明之前不应该如此),您不必担心。另一方面,如果列表在复制时有一些奇怪的副作用,您应该意识到复制构造函数调用的数量将根据编译器和设置而变化。
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.
它会起作用,但效率不高,因为可能会复制大量内存。在下一个C++标准中,这个问题可以得到解决。
我建议使用以下代码:
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:
您不能返回非简单类型(int、float、char)的本地对象,但您可以返回指向新对象的指针:
请注意,您必须管理后者的指针以避免内存泄漏。
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:
take care that you MUST manage the pointer latter to avoid memory leaks.