简体   繁体   中英

Should I inline namespace scope lambdas? In either case, why?

Sometimes I have some capture-less lambda defined at the top of a header file, which is used in the following part of the header:

//#include statements
namespace detail {
auto constexpr lambda = [](/* args */){ /* body */ };
}
// in some function or whatever, use `lambda`

Often I'm told in during code reviews that I should put not only constexpr specifier, as I do, but also the inline specifier.

Why should I do that? What are the advantages?

I've tried reading inline specifier on cppreference , but I think I lack to much terminology to understand it at the moment.

You should be using inline if the variable is defined in a header file. If it is not inline, then every translation unit that includes the header file will get that definition. That means you have multiple definitions for a single name which is an ODR ( One Definition Rule ) violation. Those do not require any diagnostics, so they can lead to hard to find bugs.

By making the variable inline, you fix the problem by telling the compiler/linker that it can throw out all of the duplicated definitions and just use a single one.

According to the C++ 17 Standard (10.1.5 The constexpr specifier)

1 The constexpr specifier shall be applied only to the definition of a variable or variable template or the declaration of a function or function template. A function or static data member declared with the constexpr specifier is implicitly an inline function or variable (10.1.6). If any declaration of a function or function template has a constexpr specifier, then all its declarations shall contain the constexpr specifier.

In the code snippet in your question the variable lambda is not a static data member.

namespace detail {
auto constexpr lambda = [](/* args */){ /* body */ };
}

So if the namespace detail has external linkage then and the variable lambda also has the external linkage. In this case if the header will be included in several compilation units then the one definition rule will be broken. To avoid such a situation you should declare the variable as an inline variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM