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.