Home > Backend Development > C++ > body text

Can Inline Member Functions Be Defined in a .cpp File and Still Be Inlined?

Patricia Arquette
Release: 2024-10-26 19:03:02
Original
615 people have browsed it

Can Inline Member Functions Be Defined in a .cpp File and Still Be Inlined?

C Inline Member Function in .cpp File: A Dilemma and Resolution

In C , inline member functions are typically declared in header files for efficiency reasons. However, certain scenarios may necessitate implementing the function in a .cpp file. Let's delve into such a situation:

Consider the following scenario with circular dependencies:

A.h

<code class="cpp">#pragma once
#include "B.h"

class A {
    B b;
};</code>
Copy after login

B.h

<code class="cpp">#pragma once

class A;

class B {
    inline A getA();
};</code>
Copy after login

To break the circular dependency, the implementation of getA needs to be placed in B.cpp:

B.cpp

<code class="cpp">#include "B.h"
#include "A.h"

inline A B::getA() {
    return A();
}</code>
Copy after login

The Dilemma

Does the placement of the inline keyword in both the header and the .cpp file affect the function's inlining?

Resolution

Unfortunately, despite the inline keyword in the .cpp file, the compiler will not inline getA unless it is used within B.cpp itself. This is because the compiler requires the definition of the inline function whenever it is encountered. Typically, placing the function in a header file ensures this availability.

Best Practice

As per C FAQ, it is imperative to define inline functions in header files. Placing them in .cpp files can lead to unresolved external errors.

Alternative Solution

The provided scenario does not suggest an alternative solution to placing the inline function in a .cpp file.

The above is the detailed content of Can Inline Member Functions Be Defined in a .cpp File and Still Be Inlined?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!