当前位置: 动力学知识库 > 问答 > 编程问答 >

by-value return in functions of c++

问题描述:

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?

网友答案:

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.

网友答案:

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);
网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: