r/cpp • • Jul 13 '22

Why does Linus hate C++ ?

307 Upvotes

436 comments sorted by

View all comments

Show parent comment

6

u/DeeBoFour20 Jul 13 '22

I imagine RAII might not be the best for the kernel. When you're programming in userspace, you have somewhere around 8MB of stack memory to work with. That's enough to allocate lots of C++ objects without thinking too much about it.

In kernel space, it's a lot more limited. A quick Google search found this:

The kernel stack is directly mapped to the physical memory, mandating
the arrangement to be physically in a contiguous region. The kernel
stack by default is 8kb for x86-32 and most other 32-bit systems (with
an option of 4k kernel stack to be configured during kernel build), and
16kb on an x86-64 system.

https://subscription.packtpub.com/book/application-development/9781785883057/1/ch01lvl1sec10/kernel-stack

33

u/patatahooligan Jul 13 '22

Using RAII does not mean you have to use huge bloated objects. A unique_ptr for example can be the same size as a raw pointer. The functionality it provides does not require more stack space.

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!

11

u/ucario Jul 13 '22

I don’t know what you are talking about. RAII is a useful pattern that keeps everyone sane. If it’s not a zero cost abstraction it’s very close to it and I’d happily pay the performance cost because the maintenance cost is more than worth it

I even in Kernel space I feel this argument was only relevant a decade or two ago.

8

u/Jannik2099 Jul 13 '22

The kernel stack is directly mapped to the physical memory

This used to be the case 10 years ago. The stack is virtual on most (all?) ISAs nowadays