开发者

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 #includ开发者_运维问答e <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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜