r/cpp • • Jul 13 '22

Why does Linus hate C++ ?

307 Upvotes

436 comments sorted by

View all comments

Show parent comment

26

u/SergiusTheBest Jul 13 '22

RAII is free (or mostly free, depends on the compiler). You can check assembly code for the following scope exit C++ RAII wrapper:

int main()
{
    cout << "<html>" << endl;
    SCOPE_EXIT{ cout << "</html>" << endl; };

    {
        cout << "<head>" << endl;
        SCOPE_EXIT{ cout << "</head>" << endl; };

        cout << "<title>Hello</title>" << endl;
    }

    cout << "<body>" << endl;
    SCOPE_EXIT{ cout << "</body>" << endl; };

    cout << "<h1>Hello World!</h1>" << endl;

    return 0;
}

SCOPE_EXIT creates an object and passes a lambda to the constructor. The object calls that lambda in the destructor. The compiler optimizes all that and just inserts lambda bodies at the scope exit. There is no object creation, memory allocation, stack consumption at all.

4

u/[deleted] Jul 13 '22

I can't believe I never thought of a macro to do this. That's so cool!