简体   繁体   English

什么时候真正内联C ++运算符?

[英]When are C++ operators really inlined?

From http://cs.brown.edu/~jak/proglang/cpp/stltut/tut.html and http://www.geeksforgeeks.org/c-qsort-vs-c-sort/ , we find that using the STL's sorting mechanism is faster than C's qsort(). http://cs.brown.edu/~jak/proglang/cpp/stltut/tut.htmlhttp://www.geeksforgeeks.org/c-qsort-vs-c-sort/中 ,我们发现使用STL的排序机制比C的qsort()快。

This is because the comparison function is "inlined". 这是因为比较功能是“内联的”。 However, when using the compiler explorer at https://godbolt.org/ to inspect the output of the gcc compiler, I can't get any operators to actually become inlined. 但是,当使用https://godbolt.org/上的编译器资源管理器检查gcc编译器的输出时,我无法让任何运算符真正内联。 See here for an example, code given below: 这里的一个例子,代码下面给出:

#include <string>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <iostream>

using namespace std;

class myClass {
    public: 

    int key;
    int data;

    myClass(int k, int d) : key(k), data(d) {}

    inline bool operator<(myClass& other) {
        return key < other.key;
    }
};

main () {
    myClass c1(1,100), c2(2, 100);
    if (c1 < c2) cout << "True" << endl;
    else cout << "False" << endl;
}

The generated assembly code clearly makes a call to the operator< routine. 生成的汇编代码显然会调用operator<例程。 The C++ compiler completely disregarded the inline keyword! C ++编译器完全忽略了inline关键字!

So when exactly are the operators inlined? 那么什么时候需要内联运算符? This is the key to having faster sorting performance for example, but it would be nice to know how to take advantage of it whenever possible. 例如,这是提高排序性能的关键,但是很高兴知道如何尽可能利用它。

Most compilers will not inline anything at all by default, because this can get in the way of debugging. 默认情况下,大多数编译器根本不会内联任何内容,因为这会妨碍调试。 You need to enable optimizations. 您需要启用优化。

gcc has a handful of levels of optimizations and many individually tweakable optimization settings, but even the simplest "-O1" flag is enough to cause your example to inline the operator< function. gcc有少量的优化级别和许多可单独调整的优化设置,但是即使是最简单的“ -O1”标志也足以使您的示例内联operator<函数。 (In fact, gcc actually realized it could determine the result of operator< at compile time, and was able to discard the else branch entirely!) (实际上,gcc实际上意识到它可以在编译时确定operator<的结果,并且能够完全丢弃else分支!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM