We have a factory function that creates a unique_ptr to some struct. The only way to return this is via a std::move but cppcheck warns us about copy elision optimization
struct Foo { std::string msg{"I'm unique :("}; }; std::unique_ptr<Foo> FooFactory() { auto foo = std::make_unique<Foo>(); return std::move(foo); } int main() { auto foo = FooFactory(); std::cout << foo->msg; }
Output:
Checking cppcheckWarnings.cpp ... cppcheckWarnings.cpp:16:20: warning: Using std::move for returning object by-value from function will affect copy elision optimization. More: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-return-move-local [returnStdMoveLocal] return std::move(foo);
Seems to work just fine without std::move: https://godbolt.org/z/M5j9KKeKd
std::move
Ah I've simplified the snippet down too much then, this is closer to what we had:
std::unique_ptr<Foo> GetFirstFoo(std::vector<std::unique_ptr<Foo>>& foos) { return std::move(foos.front()); } int main() { std::vector<std::unique_ptr<Foo>> foos; foos.emplace_back(std::make_unique<Foo>()); auto foo = GetFirstFoo(foos); std::cout << foo->msg; }
However this is rather unpleasant code as it leaves an invalid pointer in the vector so one might argue it's poor code
Thanks for reporting, this PR should fix it: https://github.com/danmar/cppcheck/pull/4244
Log in to post a comment.
We have a factory function that creates a unique_ptr to some struct. The only way to return this is via a std::move but cppcheck warns us about copy elision optimization
Output:
Last edit: Dan Workman 2022-06-29
Seems to work just fine without
std::move
:https://godbolt.org/z/M5j9KKeKd
Ah I've simplified the snippet down too much then, this is closer to what we had:
However this is rather unpleasant code as it leaves an invalid pointer in the vector so one might argue it's poor code
Thanks for reporting, this PR should fix it: https://github.com/danmar/cppcheck/pull/4244