Memory: the collector and RAII
The same program opens a connection, sends one message and closes it. In C++ the connection is an object whose destructor closes it, and the compiler inserts the call at every exit from the scope. In Go there is no destructor: the object is memory, the collector owns the memory, and the resource is closed by a defer statement that the caller writes. Both programs print the same eight lines.
RAII in C++
The destructor is the last thing that happens to the object, and it happens on every path out of the scope, including the early return in work and an exception thrown through it. Objects in a block are destroyed in the reverse order of construction, which is why the queue closes before the cache.
#include <iostream>
#include <string>
class Connection {
public:
explicit Connection(std::string name) : name_(std::move(name))
{
std::cout << "open " << name_ << "\n";
}
~Connection()
{
std::cout << "close " << name_ << "\n";
}
void send(const std::string& text) const
{
std::cout << "send " << name_ << ": " << text << "\n";
}
private:
std::string name_;
};
void work()
{
Connection db("db");
db.send("select 1");
if (true) {
return;
}
}
int main()
{
work();
{
Connection cache("cache");
Connection queue("queue");
}
std::cout << "done\n";
}
g++ -std=c++23 -O2 -Wall -Wextra raii.cpp -o raii
./raii
open db
send db: select 1
close db
open cache
open queue
close queue
close cache
done
Nothing in main calls close. That is the whole idea of RAII: the lifetime of the resource is the lifetime of a value, and the compiler already knows when a value dies.
Close and defer in Go
The same program in Go has an Open that returns a pointer and a Close that the caller must schedule. defer records the call and runs it when the surrounding function returns, also on the early return, and deferred calls run in the reverse order of their defer statements.
package main
import "fmt"
type Connection struct{ name string }
func Open(name string) *Connection {
fmt.Printf("open %s\n", name)
return &Connection{name: name}
}
func (c *Connection) Send(text string) {
fmt.Printf("send %s: %s\n", c.name, text)
}
func (c *Connection) Close() {
fmt.Printf("close %s\n", c.name)
}
func work() {
db := Open("db")
defer db.Close()
db.Send("select 1")
if true {
return
}
}
func main() {
work()
func() {
cache := Open("cache")
defer cache.Close()
queue := Open("queue")
defer queue.Close()
}()
fmt.Println("done")
}
go run ./raii
open db
send db: select 1
close db
open cache
open queue
close queue
close cache
done
The output is identical, and the difference is where the responsibility sits. The C++ compiler inserts the call; in Go the author of the caller has to write defer db.Close(), and a forgotten line leaks the connection until the process ends. That is why Go APIs that own a resource return a Close method in the same statement that creates it, and why a reviewer looks for the matching defer on the next line.
What differs and why
| Question | C++ | Go |
|---|---|---|
| When is the resource released? | When the object leaves its scope, on every path | When the function that deferred Close returns |
| Who writes the release? | The type, once, in its destructor | Every caller, as a defer line |
| What if a caller forgets? | It cannot forget | The resource stays open until the process ends |
| When is the memory reclaimed? | At the same moment, by the destructor and free | Later, by the collector, when nothing points at it |
| What does a copy mean? | Defined by the type: copy, move or delete | Values are copied; a pointer is shared, and the type says which |
The C++ model needs a rule for copying, because a type that owns a resource and is copied twice releases it twice. The rule of zero, three and five exists for that reason. Go avoids the question: a struct with a Close is almost always used through a pointer, and copying the value is not a resource operation. It moves the problem to the caller instead, which is a real trade and not a free win.
A finalizer is not a destructor
Go has a hook that looks like a destructor, runtime.SetFinalizer, and the documentation is careful: the finalizer may not run, it runs in its own goroutine at an unspecified time, and an object with a finalizer is not freed by the collection that runs the finalizer. The program below makes that last point visible, and prints the heap before and after.
package main
import (
"fmt"
"runtime"
"time"
)
type Buffer struct {
data []byte
}
func stats(label string) {
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("%s: heap %d KiB, GC runs %d\n", label, m.HeapAlloc/1024, m.NumGC)
}
func main() {
stats("start")
b := &Buffer{data: make([]byte, 1<<20)}
runtime.SetFinalizer(b, func(*Buffer) { fmt.Println("finalizer ran") })
b = nil
runtime.GC()
time.Sleep(50 * time.Millisecond)
stats("one GC")
runtime.GC()
stats("two GCs")
fmt.Println("end")
}
go run ./finalizer
start: heap 97 KiB, GC runs 0
finalizer ran
one GC: heap 1123 KiB, GC runs 1
two GCs: heap 99 KiB, GC runs 2
end
The one-megabyte buffer is still counted after the first collection, because the finalizer had just run and the object needs another cycle to be freed. It disappears after the second. The numbers move a little between runs and machines; the shape does not.
A finalizer is a safety net for a package that wraps an operating system handle, and even there the documentation recommends an explicit Close. It cannot be used for flushing a buffer, for ordering two releases or for anything a program needs to happen before it exits, because none of those is promised.
What the collector costs
The Go collector is concurrent: it runs alongside the program and stops it for very short pauses, so a request that takes ten milliseconds does not wait for a full collection. The price is paid elsewhere. The default GOGC=100 lets the heap grow to twice its live size before a collection starts, so a program with 100 MB of live data may occupy 200 MB, and the collector competes with the program for CPU. C++ pays no such tax, and pays instead with ownership rules, manual lifetime decisions and the bugs that follow a missed one.
For a service that answers requests in milliseconds, both models are fine, and the Go one is easier to review. For a program whose memory must not grow, or whose pause budget is microseconds, the collector is the reason to stay in C++. The lessons behind this page are the garbage collector and escape analysis and allocations in Go, and RAII in C++. The next page takes the same two languages to errors.
The C++ program was built with g++ 15.2.0 (Alpine 15.2.0) at -O2 and the Go programs with go 1.26.10, all run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev