防止编码器错误 - 通过参考(悬挂指针)返回临时值



如何防止编码器返回本地变量作为参考?

示例1

我有时会犯这样的错误: -

int& getStaticCache(){
    int cache = 0; return cache;  //<--- dangling pointer
}

正确的代码是: -

int& getStaticCache(){
    static int cache = 0; return cache;  //OK
}

示例2

另一种情况是: -

std::vector<Protocol>& getInternalController(){ .... some code .... }
std::vector<Protocol>& getController(){
    std::vector<Protocol> controller=getInternalController_();
    return controller;  //<--- dangling pointer
}

正确的代码是: -

std::vector<Protocol>& getController(){
    return getInternalController_();  //<--- OK
}

可能只是我,因为我在C 方面还不够熟练。
但是,这些发生一次每3个月发生一次,尤其是在糟糕的时期。

问题:哪种编程技术/设计模式/软件工程术语/C 魔术/工具/插件可以帮助我降低这种特定类型的我自己错误的速率?

我正在使用Visual Studio。

开始不忽略编译器给您的警告。

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>

这是一个"严重"(1级)警告。即使是"最不认真的"(在VS的情况下为4级)警告也可能是致命的。在最高(最低)水平的零警告中拍摄零警告。您可能无法通过更改代码来消除所有这些内容,但是您必须了解为什么给出它们。如果没有其他方法可以使它们保持沉默,并且您绝对确定它们是无害的。

,请禁用每个实例。

为什么这样做?简单:如果您每次编译代码时都会弹出一堆完全无害的警告,您将停止注意,下一个严重的警告您会引起注意。

使您的编译器将警告视为错误非常有用。作为政策,我总是在项目中启用此设置。

最新更新