Saturday, November 6, 2010

Returning a Temporary as const

A function (say func) that returns a temporary, should specify that the return type is const, so that constructs like func(2, 3) = 5; will not compile.

There are other cases where this might not possible. Here is an example from Dietmar Kuhl:

    std::auto_ptr<T> factory();
    void foo()
    {
        whatever_ptr ptr = factory();
        // ...
    }

You can't make the return value of factory() const, because assignments of an auto_ptr change the auto_ptr.

References:
  Exceptional C++ by Herb Sutter. Addison-Wesley, 1999, p. 73.
  Dietmar Kuhl, Personal Communication

No comments:

Post a Comment