如果我要在主函数之上声明和定义命名空间函数函数,如下所示,是否会导致编译器将其生成为内联函数?
我知道当我们在类声明中定义一个函数时,编译器会将该函数生成为内联函数;但是,我不确定下面显示的特定案例是否属于这种情况。有人愿意为我澄清一下情况吗?
namespace pairs_with_k_diff {
void inc_and_push_back () {
// function definition
}
}
int main() {
// Call this function inside the main later
}
最佳答案
An inline function, as far as I know, is a function which a compiler can replace those function definition wherever those are being called.
那么,让我们把这部分弄清楚。
- It tells the compiler that the function code can be expanded where the function is called, instead of effectively being called.
- It tells the compiler that the function definition can be repeated.
您显然在考虑定义 1。随着答案的继续说明,该定义不再真正使用(如果曾经使用过)。 inline
对编译器来说只意味着定义可以重复。它允许您将定义放在标题中(尽管它也可能有其他用途)。
那么,回到你原来的问题:
If I were to declare and define a namespace function function above the main function, as it is shown below, would that result in compiler generating it as an inline function?
根据您的定义,内联仅为 determined by the compiler .在这个词的这个意义上,您无法控制“内联”。
当然,如果你想要内联的其他定义,你必须声明它内联:
namespace pairs_with_k_diff {
inline void inc_and_push_back () {
// function definition
}
}
当然,如果不声明它inline
,就没有其他方法可以让这个函数“内联”(在这个词的第二种意义上)。它不会自动发生。
关于c++ - 在主函数之上定义命名空间函数是否会导致内联函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57342672/