• 第9章 在实践中使用模板:9.2 模板和内联


    9.2 Templates and inline

    9.2 模板和内联

    Declaring functions to be inline is a common tool to improve the running time of programs. The inline specifier was meant to be a hint for the implementation that inline substitution of the function body at the point of call is preferred over the usual function call mechanism.

    将函数声明为inline是提高程序性能的一种常见手段。inline修饰符是给编译器一个提示,即要优先在函数调用处用函数体作内联替换,而不是使用常规的函数调用机制。

    However, an implementation may ignore the hint. Hence, the only guaranteed effect of inline is to allow a function definition to appear multiple times in a program (usually because it appears in a header file that is included in multiple places).

    但是编译器可能会忽略这一提示。因此inline唯一可以保证的效果就是允许函数定义在程序中多次出现(通常是因为它定义于头文件,但被多个地方include)

    Like inline functions, function templates can be defined in multiple translation units. This is usually achieved by placing the definition in a header file that is included by multiple CPP files.

    与内联函数一样,可以在多个翻译单元中定义函数模板。这通常是这样来实现的:将函数模板定义在头文件,而该头文件又被多个cpp文件所包含。

    This doesn’t mean, however, that function templates use inline substitutions by default. It is entirely up to the compiler whether and when inline substitution of a function template body at the point of call is preferred over the usual function call mechanism. Perhaps surprisingly, compilers are often better than programmers at estimating whether inlining a call would lead to a net performance improvement. As a result, the precise policy of a compiler with respect to inline varies from compiler to compiler, and even depends on the options selected for a specific compilation.

    但这并不意味着函数模板在默认情况下就会被内联替换。在模板调用处是否首选用函数体inline替换而不使用普通函数调用,这件事完全是由编译器决定。令人惊讶的是,编译器在评估内联调用是否会导致程序净性能提高方面,编通常比程序员做得更好。因此,不同编译器之间对内联处理的精确策略是因编译器而异,甚至这依赖于特定的编译选项。

    Nevertheless, with appropriate performance monitoring tools, a programmer may have better information than a compiler and may therefore wish to override compiler decisions (e.g., when tuning software for particular platforms, such as mobiles phones, or particular inputs). Sometimes this is only possible with compiler-specific attributes such as noinline or always_inline.

    不过,通过合适的性能监测工具,程序员可能会比编译器更知道是否进行inline替换。同时希望由自己而不是让编译器来决定(例如,当针对移动平台或特定输入平台进行调优软件时),有时这只能使用特定于编译器的属性(如noinline或always_inline)才能做到。

    It’s worth pointing out at this point that full specializations of function templates act like ordinary functions in this regard: Their definition can appear only once unless they’re defined inline (see Section 16.3 on page 338). See also Appendix A for a broader, detailed overview of this topic.

    值得指出的是,在这一方面函数模板的完全特化和普通函数是一样的:除非被定义为inline,否则它只能被定义一次。关于这个主题更全面、更详细的阐述请参阅附录E。

  • 相关阅读:
    spring boot 2.1学习笔记【五】SpringBootTest单元测试及日志
    Java网络编程-UDP
    Java网络编程-TCP
    String的特性
    内存池的使用
    软件定时器的使用
    邮箱
    事件集
    线程优先级翻转
    临界区,互斥量与信号量
  • 原文地址:https://www.cnblogs.com/5iedu/p/12939750.html
Copyright © 2020-2023  润新知