简体   繁体   中英

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().

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. 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. The C++ compiler completely disregarded the inline keyword!

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. (In fact, gcc actually realized it could determine the result of operator< at compile time, and was able to discard the else branch entirely!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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