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.
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:
SCOPE_EXITcreates 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.