I analyzed some code with cppcheck for errors and code quality. I came across an error which I think is an false positive. The following code example shows the problem (marked with comment).
cppcheck - v 1.89
#include <string>
#include <vector>
#include <iostream>
std::string func() {
std::vector<char> data{};
data.push_back('a');
data.push_back('b');
data.push_back('c');
return std::string{ data.data(), data.size() }; // error marked here
// severity: error
// line: 12
// summary: Returning object that points to local variable 'data' that will be invalid when returning.
}
int main() {
std::string ret{};
{
ret = func();
}
std::cout << ret << std::endl;
return 0;
}
If i use ()
instead of {}
, it resolves the error.
EDIT
When I debug the example with ()
or {}
, there is totally no difference. I use Visual Studio 17 with C++14.