c++ - 在主函数之上定义命名空间函数是否会导致内联函数?

标签 c++ function namespaces inline

如果我要在主函数之上声明和定义命名空间函数函数,如下所示,是否会导致编译器将其生成为内联函数?

我知道当我们在类声明中定义一个函数时,编译器会将该函数生成为内联函数;但是,我不确定下面显示的特定案例是否属于这种情况。有人愿意为我澄清一下情况吗?

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.

那么,让我们把这部分弄清楚。

Inline has 2 definitions :

  1. It tells the compiler that the function code can be expanded where the function is called, instead of effectively being called.
  2. 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/

相关文章:

c++ - 合并 unique_ptr 的两个 vector 时“使用已删除的函数”

c# - C# 是否有一些函数可以用表单输入字符串?

c++ - g++ 在 *expected* 错误消息中给我奇怪的函数调用

postgresql - Postgres : how to create overloaded function that returns setof type

python - 在站点 url.py 中指定 Django URL-Namespaces 的原因是什么?

php - 未找到类、命名空间、子文件夹

c++ - 初学者用 Python 扩展 C(特别是 Numpy)

c++ - 如何在OpenCV C++中使用FeatureDetector?

c++ - 是否可以使用 openMP 以 O(1) 复杂度初始化 vector ? (C++)

C++ VS2010 使用命名空间并发;没有具有该名称的命名空间