Shanpei Zhou
Shanpei Zhou

Reputation: 391

return type choose in C++

In C, I think there is no reference, so the return value could be a pointer or the datatype itself. If it's a local variable, return a pointer doesn't make any sense. If the variable is dynamically allocated, only pointer can be returned.

However, in C++, there is a new choice, reference. If what I want to return is a local variable, I think I can only choose to return itself, because the other two will have nothing to refer or point to after the function return. If I dynamically allocate a variable, what do I return? Pointer or Reference? What's the advantage and disadvantage? Why don't just return the variable?

A very simple example:

class TreeNode
{
//......May be some elements and functions.
}

TreeNode& test()
{
  TreeNode* temp = new TreeNode;
  return *temp;
}

I don't what to return, pointer or reference?

Upvotes: 0

Views: 173

Answers (3)

andreaplanet
andreaplanet

Reputation: 771

If you return a reference or a pointer then you return the address of the variable.

If you return the variable then you return a copy of the variable. With big variables there is the overhead for the copy (especially when dynamically allocated, with local variables the compiler can in some circumstances optimize the code and avoid the copy).

As already said before, the difference between reference and pointer is in the syntax and rules. Basically choose which one you like most. Pointers are more explicit. With pointers you may remember that you have to deallocate a dynamic variable.

Upvotes: 0

HelloWorld123456789
HelloWorld123456789

Reputation: 5369

If you dynamically allocate a variable, you can return either the pointer or the reference.

If the variable you are returning consumes large amount of memory, it is better to return the pointer or the reference than the variable itself.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

If I dynamically allocate a variable, what do I return?

Return a pointer (a regular one or a smart one, depending on a situation). Do not return a reference to dynamically allocated objects: eventually, you will need to release the memory for the object; the construct delete &someRef that you would have to use is extremely counterintuitive.

Returning a reference is appropriate when you are returning from a member function, and a reference that you are returning is to a member, or when you are returning a reference to an object that has been passed to your function in the first place.

Why don't just return the variable?

This is a very valid choice as well: returning by value lets you not worry about memory management and object ownership. The biggest obstacle there is the cost of copying. However, their inefficiencies are are often grossly overestimated, leading to premature optimization.

Upvotes: 1

Related Questions