简体   繁体   中英

C++ Code Analysis in Visual Studio Community 2019 produces warnings C26486 and C26414

I have the following example program

#include <iostream>

class MyClass
{
private:
    int value;
public:
    MyClass(int v) noexcept : value(v) {}
    void displayValue() { std::cout << "The value is " << value; }
};

int main()
{
    auto instance{ std::make_unique<MyClass>(5) };
    instance->displayValue();
}

When I run code analysis i receive the following warning:

main.cpp(15): warning C26486: Don't pass a pointer that may be invalid to a function. Parameter 0 '@instance' in call to 'MyClass::displayValue' may be invalid (lifetime.3).

Can anyone explain to me exactly how I am supposed to be using the std::unique_ptr<MyClass> here to avoid the warning?

Additionally, I receive the following warning in the initialization of the unique_ptr:

main.cpp(14): warning C26414: Move, copy, reassign or reset a local smart pointer 'instance' (r.5).

I can alleviate this issue by wrapping the usage of std::make_unique in std::move but I don't think this should be necessary.

What is the proper way to write this code and avoid the warnings that I'm receiving from the code analyzer?

In response to warning C26414

I received a reply from Colin Robertson at Microsoft, via GitHub, with the following explanation:

This case comes under the final bullet point in the Remarks section. Unless you're doing something that needs the protection of unique_ptr, declaring it as MyClass instance{5}; avoids some needless overhead. Remember, the warning is just a reminder about a general rule. If you have a good reason for your specific declaration, be confident enough to ignore it.

His reply can also be found here for reference:

https://github.com/MicrosoftDocs/visualstudio-docs/issues/4711

So, basically, we're reminded here to not use heap allocation if it's unnecessary.

In response to warning C26486

Unanswered. I've requested more information via GitHub and am awaiting a reply.

Update 1/29/2020 - Still unanswered. Submitted issue to Microsoft Developer Community

Update 2/3/2020 - Received response from Visual Studio Community (bot, i think?) updating the status of the issue as "Triaged". I guess this means they are prioritizing the issue, maybe? If interested, you can follow the issue here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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