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.
I think the rule was for before C++11:
{/*..*/}
was only use for aggregate initialization before C++11, so T{ data.data(), data.size() }
could only store the future dangling pointer thus the diagnostic.
With T(data.data(), data.size() )
, it is a regular constructor call, so it actually depends of T
constructor, so no diagnostic can be safely be done without inspecting T
constructor (and I doubt than cppcheck does inspect) (and BTW it is safe for std::string
).
So indeed, it is a false positive.
It's a false-positive as the string ctor makes a copy of the passed char* string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With