开发者

An exception to the "only one implementation" rule?

开发者 https://www.devze.com 2023-01-03 23:59 出处:网络
While I was reading the accepted answer of this question, I had the following question: Typically, methods are defined in header files (.hpp or whatever), and implementation in source files (.cpp or

While I was reading the accepted answer of this question, I had the following question:

Typically, methods are defined in header files (.hpp or whatever), and implementation in source files (.cpp or whatever).

One of the main reasons it is bad practice to ever include a "source file" (#include <source_file.cpp>) is that its methods implementation would then be duplicated, resulting in linking errors.

When one writes:

#ifndef BRITNEYSPEARS_HPP
#define BRITNEYSPEARS_HPP

class BritneySpears
{
  public:

    BritneySpears() {}; // Here the constructor has implementation.
};

#endif /* BRITNEYSPEARS_HPP */

He is giving the implementation of the constructor (here an "empty" implementation, 开发者_如何学Pythonbut still).

But why then including this header file multiple times (aka. on different source files) will not generate a "duplicate definition" error at link time ?


Inline functions are exceptions to the "one definition rule": you are allowed to have identical implementations of them in more than one compilation unit. Functions are inline if they are declared inline or implemented inside a class definition.


Member functions with implementation inside the class definition are treated as inline functions. Inline functions are exempt from one definition rule.

Specifically when the linker sees two inline functions with the same signature it treats them as if it is the same function and just picks one of them. This can lead to really weird hard to detect problems.


Because it is an "inline" function. Inline functions can be included from headers as many times as you like and they don't cause duplicate definition linker errors.

The compiler will also try to bring them inline so, in your example above, the compiler will try and eliminate the call to the constructor completely.

0

精彩评论

暂无评论...
验证码 换一张
取 消