Question

Suppose I have the following code:

class some_class{};

some_class some_function()
{
    return some_class();
}

This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a compiler-specific thing (visual C++)? Or is this doing something wrong?

Was it helpful?

Solution

No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the temporary.

OTHER TIPS

Returning objects from a function call is the "Factory" Design Pattern, and is used extensively.

However, you will want to be careful whether you return objects, or pointers to objects. The former of these will introduce you to copy constructors / assignment operators, which can be a pain.

It is valid, but performance may not be ideal depending on how it is called.

For example:

A a;
a = fn();

and

A a = fn();

are not the same.

In the first case the default constructor is called, and then the assignment operator is invoked on a which requires a temporary variable to be constructed.

In the second case the copy constructor is used.

An intelligent enough compiler will work out what optimizations are possible. But, if the copy constructor is user supplied then I don't see how the compiler can optimize out the temporary variable. It has to invoke the copy constructor, and to do that it has to have another instance.

The difference between Rob Walker's example is called Return Value Optimisation (RVO) if you want to google for it.

Incidentally, if you want to enure your object gets returned in the most efficient manner, create the object on the heap (ie via new) using a shared_ptr and return a shared_ptr instead. The pointer gets returned and reference counts correctly.

That is perfectly reasonable C++.

This is perfectly legal C++ and any compiler should accept it. What makes you think it might be doing something wrong?

That's the best way to do it if your class is pretty lightweight - I mean that it isn't very expensive to make a copy of it.

One side effect of that method though is that it does tend to make it more likely to have temporary objects created, although that can depend on how well the compiler can optimize things.

For more heavyweight classes that you want to make sure are not copied (say for example a large bitmap image) then it is a good idea to pass stuff like that around as a reference parameter which then gets filled in, just to make absolutely sure that there won't be any temporary objects created.

Overall it can happen that simplifying syntax and making things turned more directly can have a side effect of creating more temporary objects in expressions, just something that you should keep in mind when designing the interfaces for more heavyweight objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top