简体   繁体   English

带有重载赋值运算符的 C6001

[英]C6001 with overloaded assignment operator

This simplified example code raises C6001 under static analysis:这个简化的示例代码在 static 分析下引发了 C6001:

struct st_facade
{
    st_facade &operator=(const int new_value) { m_value = new_value; return *this;}

private:
    int m_value;
};

struct foo
{
    st_facade my_int;
};

void main()
{
    foo f;
    f.my_int= 0; // C6001: Using uninitialized memory 'f'.
}

My understanding is that this warning is raised because the overloaded assignment operator hypothetically could be reading uninitialized memory.我的理解是,之所以提出此警告,是因为假设重载的赋值运算符可能正在读取未初始化的 memory。 But in this case, we are not doing that -- we are in fact initializing the memory.但在这种情况下,我们并没有这样做——我们实际上是在初始化memory。

How can I tell the compiler that the assignment operator here is not using any uninitialized memory?如何告诉编译器这里的赋值运算符没有使用任何未初始化的 memory? I've tried to express this using several different SAL annotations, but nothing has worked.我尝试使用几种不同的 SAL 注释来表达这一点,但没有任何效果。

Zero-initializing the memory (ie with foo f{}; or st_facade my_int{}; ) is not the correct answer in this case.在这种情况下,零初始化 memory(即使用foo f{};st_facade my_int{}; )不是正确的答案。 In the actual code, such initialization could have an unacceptable perf impact在实际代码中,这样的初始化可能会产生不可接受的性能影响

[edit] For similar reasons, constructor-based initialization is not the correct answer either. [编辑] 出于类似的原因,基于构造函数的初始化也不是正确的答案。 We need this type to be uninitialized on creation;我们需要这种类型在创建时未初始化; we need to inform the static analyzer that the assignment operator performs the initialization.我们需要通知 static 分析器赋值运算符执行初始化。

[edit 2] More generally, we need a way to tell the static analyzer "this method initializes the object" without implementing a constructor or zero-initializing every instance of the type. [编辑 2] 更一般地说,我们需要一种方法来告诉 static 分析器“此方法初始化对象”,而无需实现构造函数或对类型的每个实例进行零初始化。

That's why C++ have constructors.这就是 C++ 有构造函数的原因。

struct st_facade
{
    explicit st_facade(int value) 
        : m_value{ value } 
    {}
    
    st_facade &operator=(const int new_value) { m_value = new_value; return *this;}

private:
    int m_value;
};

struct foo
{
    explicit foo(int value)
        : my_int{ value }
    {}

    st_facade my_int;
};

int main()
{
    foo f{0};
}

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

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