C++ Programming

The return statement causes execution to jump from the current function to whatever function called the current function. An optional a result (return variable) can be returned. A function may have more than one return statement (but returning the same type).

Syntax
return;
return value;

Within the body of the function, the return statement should NOT return a pointer or a reference that has the address in memory of a local variable that was declared within the function, because as soon as the function exits, all local variables are destroyed and your pointer or reference will be pointing to some place in memory which you no longer own, so you cannot guarantee its contents. If the object to which a pointer refers is destroyed, the pointer is said to be a dangling pointer until it is given a new value; any use of the value of such a pointer is invalid. Having a dangling pointer like that is dangerous; pointers or references to local variables must not be allowed to escape the function in which those local (aka automatic) variables live.

However, within the body of your function, if your pointer or reference has the address in memory of a data type, struct, or class that you dynamically allocated the memory for, using the new operator, then returning said pointer or reference would be reasonable:

SOMETYPE *MyFunc()  //returning a pointer that has a dynamically 
{           //allocated memory address is valid code 
  int *p = new int[5]; 
 
  //... 
 
  return p; 
}

In most cases, a better approach in that case would be to return an object such as a smart pointer which could manage the memory; explicit memory management using widely distributed calls to new and delete (or malloc and free) is tedious, verbose and error prone. At the very least, functions which return dynamically allocated resources should be carefully documented. See this book's section on memory management for more details.

const SOMETYPE *MyFunc(int *p) 
{
  //... 
 
  return p; 
}

In this case the SOMETYPE object pointed to by the returned pointer may not be modified, and if SOMETYPE is a class then only const member functions may be called on the SOMETYPE object.

If such a const return value is a pointer or a reference to a class then we cannot call non-const methods on that pointer or reference since that would break our agreement not to change it.

Note:
As a general rule methods should be const except when it's not possible to make them such. While getting used to the semantics you can use the compiler to inform you when a method may not be const -- it will (usually) give an error if you declare a method const that needs to be non-const.

Last modified on 20 August 2010, at 17:37