Code 1:

#include<iostream>
using namespace std;

int& func()
{
	int a=6;
	return a;
}

int main(void)
{
	int a = func();
	cout<<a;
     
      cin.get();
      return 0;
}

According to my thought , first of all func() will create a temporary reference to a (as it is returning by reference) , and then through that temporary reference it will provide value to a.

Please correct me if I'm wrong!


Code 2:

#include<iostream>
using namespace std;

int& func()
{
	int a=6;
	return a;
}

int main(void)
{
	int& a = func();
	cout<<a;
     
      cin.get();
      return 0;
}

I think this time too func will create a temporary and assign value to a as a reference.But after function is returned shouldn't func value be trashed ?
How 'a' in main is still printing correct values ?

Please somebody explain.

Regards!

Dani AI

Generated

Both examples invoke undefined behavior: a function must not return a reference to a local automatic object. When the function exits, the local object is destroyed and any reference or pointer to its storage dangles. , the idea of a “temporary reference” created inside the function is incorrect — there is no lifetime extension in that case. is right that the value can appear to “work” by coincidence because the stack slot hasn’t been overwritten yet; that coincidence is not reliable. See the C++ object lifetime rules and undefined behavior for details (object lifetime, undefined behavior).

Quick clarification about the two cases in the thread: when you write int a = func(); the program reads from the dangling reference once to copy a value into a — that read is already undefined. When you write int& a = func(); the reference in main is bound to invalid storage and every access of a is undefined. Different compilers, optimization levels or platforms may show different symptoms (correct value, garbage, crash).

Safe alternatives:

  • Return by value (for small types the compiler will elide copies):
    int func_value() {
      int x = 6;
      return x;
    }
  • Return a reference to an object with adequate lifetime (static/global), with care:
    int& func_static() {
      static int x = 6;
      return x;
    }
  • Return ownership via a smart pointer:
    std::unique_ptr<int> func_ptr() {
      return std::make_unique<int>(6);
    }

Practices: enable warnings (-Wall -Wextra, compiler-specific -Wreturn-local-addr / -Wreturn-stack-address), use sanitizers (-fsanitize=address,undefined) and static analysis. Prefer returning by value or using well-defined ownership/lifetime so behavior is predictable.

Recommended Answers

All 3 Replies

Both of your examples are wrong: A function must never return a reference to a local variable. Whatever output such a program produces is the result of coincidence and cannot be trusted.

Please threw some light how actually this coincidence does happen ?

The usual way is that the variable's memory has been deallocated but the program hasn't gotten around to putting anything new in that particular piece of memory yet. So by luck it still has the last value you gave it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.