c++ - 如果我将一个大函数声明为内联函数怎么办?

标签 c++ performance inline

我搜索了一些相关问题(例如Benefits of inline functions in C++?),但我仍然有问题。

如果内联函数只是为了“为编译器提供一种简单的机制来应用更多的优化”。

  1. 那我可以把每个函数都设置为内联函数吗?
  2. 如果我错误地将一个函数设置为内联函数,性能会怎样?
  3. 任何阈值告诉我什么大小的函数不应该是内联函数?

最佳答案

仅使用 inline 来满足单一定义规则。出于性能原因,不要为 inline 而烦恼。

If inline function is just to "provide a simple mechanism for the compiler to apply more OPTIMIZATIONS."

如果我们谈论的是 inline 关键字,那么这不是 inline 是关于什么的。就像,完全一样。

inline 所做的 是确保函数不违反单一定义规则。它还可能向编译器提供提示,提示编译器应该将代码内联处理掉,这可能会提高速度,也可能不会提高速度,但编译器有权忽略该提示。事实上,在现代编译器中,他们会在很多时候忽略这个提示。

编译器很可能不会将内联代码炸掉的情况之一是大函数。这并不意味着该函数不应该被声明为inline,但这完全取决于函数的声明、定义和使用方式。但是,同样,它与性能无关

在应用优化技术时,不要试图超越编译器。它比你更擅长让你的程序更快。


让我们看看标准对这一切的看法。

7.1.2 函数说明符

2/A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.

这告诉我们,inline 是对编译器的请求,要求编译器以内联方式删除代码,并且不需要编译器执行该替换。但这也告诉我们,无论编译器执行这种内联替换,7.1.2 中定义的“其他规则”仍然适用。

很久以前,C++ 编译器采用的优化技术相对于今天的编译器来说还很原始。在那些日子里,使用 inline 作为优化技术可能是有意义的。但是如今,编译器在优化代码方面做得更好。编译器应用的技术在今天可以使您的代码比内联更快,即使该函数实际上并未内联。 (一个可能的例子,RVO。)

因此最终结果是,虽然 7.1.2/2 的初衷可能是为程序员提供手动优化技术,但现代编译器的优化如此激进,以至于这一初衷在很大程度上没有实际意义。

因此,inline 剩下的就是那些“其他规则”。那么其他规则是什么? (C++11 措辞)

4/An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2). [ Note: A call to the inline function may be encountered before its definition appears in the translation unit. — end note ] If the definition of a function appears in a translation unit before its first declaration as inline, the program is ill-formed. If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required. An inline function with external linkage shall have the same address in all translation units. A static local variable in an extern inline function always refers to the same object. A string literal in the body of an extern inline function is the same object in different translation units. [ Note: A string literal appearing in a default argument is not in the body of an inline function merely because the expression is used in a function call from that inline function. — end note ] A type defined within the body of an extern inline function is the same type in every translation unit.

让我们来看一个例子。假设我们有这个类 template:

文件:foo.h

#ifndef FOO_H     
#define FOO_H     

#include <string>     
#include <sstream>     

class StringBuilder    
{    
public:    
    template <typename T> inline StringBuilder& operator<<(const T& t)    
    {    
        mStream << t;    
        return * this;    
    }    
    operator std::string () const;    
private:    
    std::stringstream mStream;    
};    

StringBuilder::operator std::string() const     
{     
    return mStream.str();    
}     

#endif     

如果我们在 main.cpp#include 这个文件并使用 StringBuilder,一切都很好:

文件:main.cpp

#include <iostream>
#include <string>

int main()
{
    double d = 3.14;
    unsigned a = 42; 

    std::string s = StringBuilder() 
        << "d=" << d << ", a=" << a;
    std::cout << s << "\n";
}

输出:

jdibling@hurricane:~/dev/hacks$ ./hacks 
d=3.14, a=42

但是如果我们想在第二个翻译单元中使用 StringBuilder,我们就会遇到问题:

文件:其他.cpp

#include <iostream>
#include <string>

#include "foo.h"

void DoSomethingElse()
{
    unsigned long l = -12345;
    long l2 = 223344;

    std::string s = StringBuilder()
        << "l=" << l << ", l2=" << l2; 
    std::cout << s << "\n";
}

编译器输出:

ninja: Entering directory `.'
[1/3] Building CXX object CMakeFiles/hacks.dir/main.o
[2/3] Building CXX object CMakeFiles/hacks.dir/other.o
[3/3] Linking CXX executable hacks
FAILED: : && /usr/bin/g++   -Wall -std=c++11 -g   CMakeFiles/hacks.dir/main.o CMakeFiles/hacks.dir/other.o  -o hacks  -rdynamic -lboost_regex-mt && :
CMakeFiles/hacks.dir/other.o: In function `std::operator|(std::_Ios_Openmode, std::_Ios_Openmode)':
/home/jdibling/dev/hacks/foo.h:21: multiple definition of `StringBuilder::operator std::string() const'
CMakeFiles/hacks.dir/main.o:/home/jdibling/dev/hacks/foo.h:21: first defined here
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

StringBuilder::operator std::string() 被定义了两次;一次在 main.cpp 中,一次在 other.cpp 中——这违反了单一定义规则。

我们可以通过使函数内联来解决这个问题:

class StringBuilder
{
public:
    // [...]
    inline operator std::string () const;
//  ^^^^^^
private:
    std::stringstream mStream;
};

编译器输出:

ninja: Entering directory `.'
[1/3] Building CXX object CMakeFiles/hacks.dir/main.o
[2/3] Building CXX object CMakeFiles/hacks.dir/other.o
[3/3] Linking CXX executable hacks

这是有效的,因为现在 operator std::string 在两个翻译单元上定义了完全相同的定义。它与直接在声明中定义函数具有相同的效果:

class StringBuilder
{
public:
    operator std::string () const
    {
        return mStream.str();
    }
private:
    std::stringstream mStream;
};

关于c++ - 如果我将一个大函数声明为内联函数怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632883/

相关文章:

c++ - 无法将参数从 'int' 转换为 'int&'

java - 计时器加载另一个 Activity 需要多长时间

Django 获取内联表单管理员中的实例

css - 对齐内嵌 block Div 中的文本? CSS

c++ - 如何创建 constexpr std::vector<std::string> 或类似的东西?

c++ - 纯虚函数的继承

c++ - 在 C++ 中的字符串中搜索字符串

android - 他们同时启动两个连续服务是否有任何负面影响?如果是这样,有哪些替代方案?

mysql: 使用 sort_union(sourceClass,destinationClass);在解释计划中

c++ - 在内联函数中调用外部函数