gpt4 book ai didi

c++ - 什么时候函数应该内联?

转载 作者:行者123 更新时间:2023-12-02 10:01:38 25 4
gpt4 key购买 nike

假设我在头文件中声明了以下类,并带有友元函数 swap :

// header.h
class myClass
{
friend void swap(myClass &, myClass &);

public:
myClass(int ii = 0) : i(ii) {}

private:
int i;
};

现在我想定义 swap .如果我稍后在同一个头文件中定义它,
inline void swap(myClass &a, myClass &b)
{
using std::swap;
swap(a.i, b.i);
}

一切安好。但如果我 删除 inline说明符,我收到一个错误。

现在说我想定义 swap在一个单独的实现文件中。如果我这样定义,
// impl.cc
#include "header.h"
void swap(myClass &a, myClass &b)
{
using std::swap;
swap(a.i, b.i);
}

一切安好。但是现在如果我 添加 inline说明符,我收到一个错误。

为什么需要一个版本 inline但其他版本不能有吗?

最佳答案

来自 C++ 标准(9.1.6 内联说明符)

6 If an inline function or variable is odr-used in a translation unit, a definition of it shall be reachable from the end of that translation unit, and it shall have exactly the same definition in every such translation unit (6.2). [Note: A call to the inline function or a use of the inline variable may be encountered before its definition appears in the translation unit. —end note] If a definition of a function or variable is reachable at the point of its first declaration as inline, the program is ill-formed. If a function or variable with external or module linkage is declared inline in one translation unit, there shall be a reachable inline declaration in all translation units in which it is declared; no diagnostic is required. An inline function or variable with external or module linkage shall have the same address in all translation units. [Note: A static local variable in an inline function with external or module linkage always refers to the same object. A type defined within the body of an inline function with external or module linkage is the same type in every translation unit. —end note]



因此,您要么在 header 中将友元函数声明为内联函数,以便在使用它的每个翻译单元中都可以访问其定义。或者该函数是一个非内联函数,其定义应放在一个编译单元中以满足一个定义规则。

关于c++ - 什么时候函数应该内联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62296068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com