Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lambda constructor shows uneccesary copies #347

Closed
andreasfertig opened this issue Sep 26, 2020 · 0 comments
Closed

Lambda constructor shows uneccesary copies #347

andreasfertig opened this issue Sep 26, 2020 · 0 comments
Labels
bug Something isn't working

Comments

@andreasfertig
Copy link
Owner

I was made aware of the following example by @fenbf:

#include <string>

int main() {
std::string str {"Hello World"};
auto foo = [str]() { };
}

C++ Insights currently shows this transformation:

#include <string>

int main()
{
  std::string str = std::basic_string<char, std::char_traits<char>, std::allocator<char> >{"Hello World", std::allocator<char>()};
    
  class __lambda_5_12
  {
    public: 
    inline /*constexpr */ void operator()() const { }
    
    private: 
    std::basic_string<char, std::char_traits<char>, std::allocator<char> > str;
    public: 
    __lambda_5_12(std::basic_string<char, std::char_traits<char>, std::allocator<char> > _str)
    : str{_str}
    {}
  };
  
  __lambda_5_12 foo = __lambda_5_12{std::basic_string<char, std::char_traits<char>, std::allocator<char> >(str)};
}

There the constructor of __lambda_5_12 takes the arguments by copy. However, the Standard requires direct-initialization.
This is an area where the compiler is mightier than what developers can express in C++. The best option is to taken the parameters by reference or const reference. Some cases where variables are moved into captures still create an additional move.

Andreas

andreasfertig added a commit that referenced this issue Sep 26, 2020
Fixed #347: Use `const &` or `&/&&` as constructor parameters for lambdas
@andreasfertig andreasfertig added the bug Something isn't working label Sep 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant