c++syntaxreturn-by-reference

Returning by reference in C++


I know that it's alright to return by reference if the referenced variable was also passed into the function by reference. For example:

int& foo(int& bar)
{
    bar++;
    return bar;
}

However, I'm wondering if it's possible to also return by reference if you're returning an object that was created in the function via the new keyword. I tried something like the following, but got a compiler error:

vector<int>& baz()
{
    return new vector<int>();
}

Is there a way to return the new vector by reference that makes sense, or is it better to just return a pointer?


Solution

  • Technically, you can of course return a dynamically allocated object by reference:

    vector<int>& baz()
    {
        return *new vector<int>();
    }
    

    Note the * used to dereference the pointer returned by new.

    Whether it's wise to do that is an entirely different kettle of fish. It's a prime candidate for a memory leak. If you do it, the caller is responsible for calling delete on the returned object, otherwise it's leaked. Note that this could happen very easily with either of these scenarios:

    std::vector<int> v1 = baz(); // leak!
    auto v2 = baz(); // leak!, auto doesn't deduce references
    

    In modern C++, you should simply return the vector by value and let move semantics and/or (Named) Return Value Optimisation do its job:

    std::vector<int> baz()
    {
      return std::vector<int>();
    }
    

    If you need dynamic allocation for some reason, you should at least return a suitable smart pointer to ensure no memory leaks can happen:

    std::unique_ptr<std::vector<int>> baz()
    {
      return std::unique_ptr<std::vector<int>>(new std::vector<int>());
    }