Encapsulation Safety

Consider the following example:

void f() {
	C c;
	C *p = new C;
	g();
	delete p;
}

There seem to be no leaks, but what if g throws an exception?

void f() {
	C c;
	C *p = new C;
	try {
		g();
	}
	catch (...) {
		delete p;
		throw;
	}
}

This solves the problem, but still ugly.

What other solutions are there?

C++ Idiom - RAII (Resource Acquisition Is Initialization)

Every resource should be wrapped in a stack-allocated object, whose job is to delete it

Unique and Shared Pointers

Unique Pointers

We guarantee that there are no leaks!

import <memory>

void f() {
	C c;
	std::unique_ptr<C> p {new C};
	g();
}