I don’t have a feeling (yet, I hope) for whether to chose value or reference semantics in some situations. Is there any rule of thumb I can apply?
I usually pick references for everything other than the built-in data types (char, int, bool, double etc.). However, sometimes it’s not possible to return references from a function, so I would have to use pointers. The following function is an example of this:
Foo bar()
{
Foo f;
f.do_stuff();
return f;
}
I’d use boost::shared_ptr to store the Foo object, but it makes working with the object quite ugly. I’m currently looking at a function that returns a deque that will hardly ever have more than 10 elements (that’s what I assume, I have no way of making sure). Would it be OK to return this by value? Are my considerations a case of premature optimization?
Returning by value is fine, since most compilers will optimize the extra copy away (this is called Return Value Optimization, or rather Named Return Value Optimization in your case).
But the idiomatic way is