October 7, 2023
C++ RAII optimization
Wanted to check my assumptions on C++ and the ability of modern compilers to optimize RAII (side note: I can never remember that abbreviation, always have to google it), so this morning I had a few moments of fun with godbolt:
extern int gv, bar();
template<class T> class saver {
public:
T save, *ptr;
saver(T *p) : ptr(p) { save = *p; }
~saver() { *ptr = save; }
};
void foo_c() {
int save = gv;
gv = 1;
bar();
gv = save;
}
void foo_cxx() {
saver<int> s(&gv);
gv = 1;
bar();
}
When compiled with -O2 -fomit-frame-pointer -fno-exceptions, would foo_c() and foo_cxx() differ meaningfully?
Output (x86-64 gcc 4.7.4, newer gcc versions are all similar):
foo_c():
push rbx
mov ebx, DWORD PTR gv[rip]
mov DWORD PTR gv[rip], 1
call bar()
mov DWORD PTR gv[rip], ebx
pop rbx
ret
foo_cxx():
push rbx
mov ebx, DWORD PTR gv[rip]
mov DWORD PTR gv[rip], 1
call bar()
mov DWORD PTR gv[rip], ebx
pop rbx
ret
So yeah, the optimizer does perfectly.
Recordings:
Yes, Exactly, Yes! - 1 -- [8:53]
Yes, Exactly, Yes! - 2 - Private Life -- [7:20]
Yes, Exactly, Yes! - 3 - Watch Your Step -- [2:46]
Yes, Exactly, Yes! - 4 - Watch Your Step (II) -- [2:05]
Yes, Exactly, Yes! - 5 - Self Imposed -- [4:39]
Yes, Exactly, Yes! - 6 - Dogs Will Rule the World -- [3:04]
Yes, Exactly, Yes! - 7 - Virgins Again -- [2:53]
Yes, Exactly, Yes! - 8 - Virgins Again (Again) -- [3:14]
Yes, Exactly, Yes! - 9 - The River -- [4:31]
Yes, Exactly, Yes! - 10 - Cosmic Background -- [3:32]
Yes, Exactly, Yes! - 11 -- [5:20]
Yes, Exactly, Yes! - 12 - Hindenburg -- [6:42]
Yes, Exactly, Yes! - 13 - Chosen by the Few -- [3:48]
Yes, Exactly, Yes! - 14 - Las Vegas -- [4:04]
Yes, Exactly, Yes! - 15 - No Big Benefactor -- [4:06]
Yes, Exactly, Yes! - 16 - Now We Understand -- [4:14]
Yes, Exactly, Yes! - 17 - Cast Iron Candy Bandit -- [3:10]
Yes, Exactly, Yes! - 18 - Dogs Will Rule the World (reprise) -- [3:37]
Yes, Exactly, Yes! - 19 - Find Me -- [5:01]
Yes, Exactly, Yes! - 20 - Old as Coal -- [4:33]
Yes, Exactly, Yes! - 21 -- [11:36]
Yes, Exactly, Yes! - 22 - Charlie (feat Cory Choy) -- [4:35]