Duplicate characters with header-only implementation

I have a C ++ class that is declared and implemented in a header file. I chose this because you cannot easily navigate between Debug and Release builds because of _GLIBCXX_DEBUG and precompiled libraries. For example, if I define _GLIBCXX_DEBUG , Boost will fail due to ABI changes in the source files.

Implementing only the header created a problem with duplicate characters. For example, in the class below, operator== and a non-member swap will produce multi-valued characters.

 // Foo.hpp namespace Bar { template class Foo { ... }; bool operator==(const Foo& a, const Foo& b) { .. } } namespace std { template <> void swap(Bar::Foo& a, Bar::Foo& b) { a.swap(b); } } 

When the declaration and implementation were separated, the files (Foo.hpp and Foo.cpp) were compiled and linked OK.

What is the trick to get this to compile and link correctly?

+4
source share
1 answer
 inline bool operator==(const Foo& a, const Foo& b) { .. } 

Member functions are implicit built-in if defined inside their class. The same is true for them: if they can be placed in the headline without the hassle, you can really do it.

Since the function code is placed in the header and visible, the compiler can embed calls in them, that is, put the function code directly on the call site (not so much because you inserted it before it, but more because the compiler solves this way, though. Input inline only hints for the compiler regarding this). This can lead to better performance, because the compiler now sees where the arguments correspond to variables local to this function, and where the argument is not aliased to each other - and, last but not least, the assignment of function frames is no longer required.

+5
source

Source: https://habr.com/ru/post/1446862/


All Articles