I have written some test code to use with the c++ guidelines code checker in vs2019. I get the following warnings and I am not sure how to get rid of them.
Line 60 - warning C26486: Don't pass a pointer that may be invalid to a function. Parameter 0 '@@v' in call to 'icall' may be invalid (lifetime.3).
line 79 warning C26486: Don't pass a pointer that may be invalid to a function. Parameter 0 '@a' in call to 'icall' may be invalid (lifetime.3).
#include <memory>
#include <string>
#include <iostream>
#include <vector>
using namespace::std;
class IReconQElem {
public:
virtual string getDesc() = 0;
};
class classA : public IReconQElem {
public:
int a;
int b;
string desc;
string getDesc() override {
return desc;
}
classA(int a) noexcept {
this->a = a;
b = 0;
}
virtual ~classA() {
}
};
static void g(string a) {
cout << a;
}
typedef shared_ptr<IReconQElem> IReconQElemPtr;
typedef vector<IReconQElemPtr> IReconQElemPtrsV;
IReconQElemPtrsV v;
static IReconQElemPtr func(IReconQElemPtr tid)
{
v.push_back(tid);
IReconQElemPtr ptr;
for (auto& elem1 : v) {
g(elem1->getDesc()); //this generates the warning
break;
}
return ptr;
}
int main()
{
IReconQElemPtr tid = make_shared<classA>(1);
IReconQElemPtr tid1 = make_shared<classA>(2);
v.push_back(tid);
v.push_back(tid1);
auto a = func(tid);
auto a1 = func(tid1);
auto copy = a;
g(a->getDesc()); //this generates the warning
return 0;
}
The warning is correct, elem1
in func
and a
in main
could both be a shared_ptr
holding a nullptr
. You could use gsl::not_null
to make clear that the pointer can't be nullptr
.
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.