简体   繁体   English

删除警告 C6001

[英]Remove the warning C6001

I am using VS2017 and do not understand why I am getting compiler "Warning C6001 Using uninitialized memory 'values'", on line if(values!= NULL) in catch block.我正在使用 VS2017,但不明白为什么我在 catch 块中的 if(values!= NULL) 线上得到编译器“警告 C6001 使用未初始化的内存‘值’”。

#include <windows.h>

typedef enum 
{        
   VALUE_STATE_NOT_AVAILABLE = 1,
   VALUE_STATE_ERROR         = 2,
   VALUE_STATE_VALID         = 3,
   VALUE_STATE_UNKNOWN       = 4
} XyzValueState_t;
    
class XyzValue
{
    private:    XyzValueState_t     _valueState;
    protected:  XyzValue( XyzValueState_t valueState )  {
                    _valueState = valueState;
                }
}

typedef XyzValue* xyzValuePtr_t;

main(){
    bool flag=true;
    xyzValuePtr_t* values = NULL;
    unsigned int _argument=2;
    if(flag==true)  {
        values = new PCLValuePtr_t[2]{ NULL,NULL }; 
        try     {
            values[0] = new PCLUnsignedInteger(_argument);
            values[1] = new PCLUnsignedInteger(_argument);
            xyz(values);    // passing the value to third party function which returns void
        }
        catch(...)  {
            if(values!= NULL){
                for(int k = 0; k < 1; k++)  {
                   delete values[k];
                   values[k] = NULL;      
                }
                delete [] values;
                values = NULL;
            }
        }
    }
}

Thank you in advance for your help and guidance提前感谢您的帮助和指导

not quite sure why your compiler thinks this might be unitialized.不太确定为什么您的编译器认为这可能是未初始化的。

But, in C++, I'd argue that the way you're building your array with new is unnecessarily complicated and error prone.但是,在 C++ 中,我认为使用new构建数组的方式不必要地复杂且容易出错。 This look like someone from 1993 tried to write C++11.这看起来像是 1993 年的某个人试图编写 C++11。 You have initializer lists, but you don't use RAII!你有初始化列表,但你不使用 RAII!

so, do the C++ thing and use C++'s deterministic object lifetime to manage memory.所以,做 C++ 的事情并使用 C++ 的确定性对象生命周期来管理内存。 For an array of objects, this is elegantly handled by std::vector :对于对象数组,这由std::vector优雅地处理:

#include <vector>
class XyzValue;

main(){
    bool flag=true;
    unsigned int _argument=2;
    if(flag==true)  {
        std::vector<XyzValue> values(2);  // default initialization for two XyzValues.
        try     {
            xyz(values.data());    // if you need the raw contiguous memory. **You probably don't.**
        }
        catch(...)  {
// all the manual deletion not necessary anymore, because at end of scope, things are deconstructed automatically, so this catch clause now is empty.
        }
    }
}

See how this is much shorter, better readable, has the same functionality, but none of the need to manually delete anything?看看这如何更短、更易读、具有相同的功能,但不需要手动删除任何内容? That's why we write C++ instead of C.这就是我们编写 C++ 而不是 C 的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM