Menu

FP: returnStdMoveLocal of unique_ptr

2022-06-29
2022-06-30
  • Dan Workman

    Dan Workman - 2022-06-29

    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);
    
     

    Last edit: Dan Workman 2022-06-29
  • CHR

    CHR - 2022-06-29

    Seems to work just fine without std::move:
    https://godbolt.org/z/M5j9KKeKd

     
  • Dan Workman

    Dan Workman - 2022-06-29

    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

     
  • CHR

    CHR - 2022-06-30

    Thanks for reporting, this PR should fix it: https://github.com/danmar/cppcheck/pull/4244

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.