1

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?

user2752467
  • 864
  • 5
  • 16
  • 7
    There is no way that would make sense. It would actually make more sense to return the vector by value, then the caller doesn't have to read the docs to figure out it they need to delete the object. – juanchopanza Oct 15 '14 at 20:07

3 Answers3

6

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>());
}
M.M
  • 138,810
  • 21
  • 208
  • 365
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

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

A double no no.

Just return by value and take advantage of copy-elision (See: What are copy elision and return value optimization?) and move-semantics (See: What are move semantics?)

Community
  • 1
  • 1
1
new vector<int>();

actually returns a pointer.

If you really like to memory leak, write this:

return *(new std::vector<int>());
jimifiki
  • 5,377
  • 2
  • 34
  • 60