内联是否将函数/方法限制在其当前源文件的范围内

Does Inline restrict the function/method to the scope of its current source file?

本文关键字:源文件 范围内 是否 函数 方法      更新时间:2023-10-16

假设我的程序中有以下内容,

// namespaceB.h
#include "namespaceA.h"
namespace B {
class Tree {
    public:
    Tree *prev;
    Tree *next;
    Tree *down;
    A::Kind kind;
    Tree();
    ~Tree();
};
}
// end of namespaceB.h
// Implementation details of the class are placed in namespaceB.cc
// Constructor / Desctructor defined in the namespaceB.cc file!
// Something like this,
#include "namespaceB.h"
namespace B {
inline Tree::Tree() { ... }
inline Tree::~Tree() { ... }
}

我的问题是,内联ctor/dtor是否将它们的使用限制在当前源文件中?

我认为内联只是提高效率的一种方式?

如果Tree有一个类似的memeber方法呢

Tree& Tree::operator+(Tree const& rhs);

在头文件和源文件中定义

inline Tree& Tree::operator+(Tree const& rhs) { ... }

我玩了一下,这里似乎"内联"也将Tree::operator+(…)限制在源文件的范围内

这意味着这将失败:

#include "namespaceB.h"
int main() {
B::Tree tree;    // Fail to link
return 0;    
}

如图所示:无法从另一个命名空间创建类的实例?

在我从类Tree的ctor/dtor中删除"inline"之后,所有内容都得到了完美的编译和链接。

有人能解释一下内联到底是干什么的吗?

谢谢,

如果将函数标记为内联,则必须将其包含在使用该函数的每个源文件中。

C++11标准是这样说的:

7.1.2/4:"应在odr使用的翻译单位,应具有在每种情况下都有相同的定义。"