One of the situations where C++ can trip beginner programmers is with the unconscious use of dangling references. A dangling reference is a situation where you end up with a reference to a variable that does not exist in memory any longer.
Consider the example below,
const int& min(const int& i1, const int& i2)
{
if (i1 < i2)
return (i1);
return (i2);
}
int main()
{
const int& i = min(1+2, 3+4);
return (0);
}
Before the function min is called, a temporary variable is created to hold the value of the expression 1 + 2. A reference to this temporary variable is passed to the min function as the parameter i1. Similarly, another temporary variable is created for the parameter i2.
After the function min is executed, it returns a reference to i1. But this is a temporary variable that C++ created in main. Temporary variables are destroyed by C++ at the end of the statement where they were created. This means that in the above example, i points to something that does not exist. This is called a dangling reference and can cause problems that may be difficult to detect especially for beginner programmers. So C++ programmers beware of such dangling references.
Related Posts:
Tags: programming

