How to prevent coder from returning local variable as reference?
Example 1
I sometimes make a mistake like this :-
int& getStaticCache(){
int cache = 0; return cache; //<--- dangling pointer
}
The correct code is :-
int& getStaticCache(){
static int cache = 0; return cache; //OK
}
Example 2
Another case is :-
std::vector<Protocol>& getInternalController(){ .... some code .... }
std::vector<Protocol>& getController(){
std::vector<Protocol> controller=getInternalController_();
return controller; //<--- dangling pointer
}
The correct code is :-
std::vector<Protocol>& getController(){
return getInternalController_(); //<--- OK
}
It may be just me, because I am not skillful in C++ enough.
However, these occur to me once every 3 months, especially in bad time.
Question: What programming technique / design pattern / software engineering jargon / C++ magic / tool / plugin that can help me reduce the rate of this specific type of my own mistake?
I am using Visual Studio.
Start with not ignoring warnings the compiler gives you.
c:\CODE>type bad.cpp
int& foo()
{
int a = 42;
return a;
}
c:\CODE>cl /c bad.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
bad.cpp
bad.cpp(4) : warning C4172: returning address of local variable or temporary
c:\CODE>
This is a "severe" (level 1) warning. even the "least serious" (level 4 in case of VS) warnings can be deadly. Shoot for zero warnings at thhe highest (least serious) level. You may not be able to eliminate all of them by changing your code, but you have to understand why they are given. Disable each instance on a case-by-case basis if there is no other way to silence them and you are absolutely sure they are harmless.
Why do so? Simple: if you have a bunch of totally harmless warnings popping up each time you compile your code, you stop paying attention and the next serious warning you introduce goes unnoticed.
Making your compiler treat warnings as errors is very useful. I always enable this setting in my projects as a matter of policy.