在c++中添加内联函数以提高性能

objective c - extern inline functions in C++ for performance

本文关键字:函数 高性能 c++ 添加      更新时间:2023-10-16

我有以下场景我有一个。cpp文件(我需要使用这些实际上在objective - c++ .mm):

#include <utility>
bool g_ready;
std::pair<int, bool> g_pair;
extern inline bool& isReady()
{
    return g_ready;
}
extern inline std::pair<int, bool>& GetPair()
{
    return g_pair;
}
extern inline void SetPair(int i, bool b)
{
    g_pair.first = i;
    g_pair.second = b;
}

然后我在另一个。cpp文件中使用这些:

#include <iostream>
extern inline bool& isReady();
extern inline std::pair<int, bool>& GetPair();
extern inline void SetPair(int i, bool b);
void update()
{
    if (isReady())
    {
         SetPair(5, false);
         std::cout << "<" << GetPair().first << "," << GetPair().second << ">" << std::endl;
         SetPair(1, true);
         std::cout << "<" << GetPair().first << "," << GetPair().second << ">" << std::endl;
    }
}

我需要这些函数在每帧调用的Update循环中被调用。这是最优解吗?这些会在没有任何运行时开销的情况下内联吗?

编辑:产品编译器是Clang for iOS

这是最优解吗?

。内联函数必须在使用它们的每个翻译单元中定义,无论它们是否具有外部链接(默认情况下它们将具有外部链接,无需指定extern)。因为这个原因,你的代码给了我一个链接错误。

这些将实际上内联没有任何运行时开销吗?

这取决于编译器。短inline函数(必须在与调用相同的单元中定义)通常为;只有当编译器支持链接时优化时,其他翻译单元中的函数才能内联。