tomermes
tomermes

Reputation: 23380

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?

Upvotes: 0

Views: 168

Answers (3)

Gustavo V
Gustavo V

Reputation: 152

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.

Upvotes: -1

daramarak
daramarak

Reputation: 6155

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.

Upvotes: 1

Drakosha
Drakosha

Reputation: 12165

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);

Upvotes: 1

Related Questions