Can references refer to invalid location in C++?
In C++, Reference variables are safer than pointers because reference variables must be initialized and they cannot be changed to refer to something else once they are initialized. But there are exceptions where we can have invalid references.
1) Reference to value at uninitialized pointer.
int *ptr; int &ref; = *ptr; // Reference to value at some random memory location |
chevron_right
filter_none
2) Reference to a local variable is returned.
int& fun() { int a = 10; return a; } |
chevron_right
filter_none
Once fun() returns, the space allocated to it on stack frame will be taken back. So the reference to a local variable will not be valid.
Please write comments if you find anything incorrect in the above GFact or you want to share more information about the topic discussed above.
Recommended Posts:
- References in C++
- C++ | References | Question 6
- C++ | References | Question 4
- C++ | References | Question 6
- Pointers vs References in C++
- C++ | References | Question 6
- C++ | References | Question 1
- Default Assignment Operator and References
- Variables in C++
- Implementing Forward Iterator in BST
- Count substrings that contain all vowels | SET 2
- Machine Learning in C++
- How can we use Comma operator in place of curly braces?
- Basic Code Optimizations in C



