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?