Resource Acquisition Is Initialization
Thameera Senanayaka
Allion Technologies
void render()
{
LEParam* oLeParam = new LEParam();
// ...
delete oLeParam;
}
What if an exception is thrown in the middle of the code?
void getData()
{
Database db = new Database(URI);
db.connect();
// ...
db.close();
}
std::mutex mu;
void f()
{
mu.lock();
// ...
mu.unlock();
}
Aishwarya Raii
class Lock
{
public:
Lock(std::mutex &mu) : mu_(mu) { mu_.lock(); }
~Lock() { mu_.unlock(); }
private:
std::mutex &mu_;
};
Lock a(&mu);
Lock b(a);
or
class Lock
{
public:
Lock(std::mutex &mu) : mu_(mu) { mu_.lock(); }
~Lock() { mu_.unlock(); }
private:
std::mutex &mu_;
Lock(Lock const &); // copy ctor
Lock& operator=(Lock const &); // copy assignment ctor
};
In Preprocessor,
startup::core::memory::ScopedPtr
Use a custom deleter
std::shared_ptr<T>(obj, deleter);
void custom_deleter(Image* img)
{
delete img;
}
shared_ptr<Image> img(new Image(), custom_deleter);
std::shared_ptr<Image> img(new Image(), [](Image *img) {
delete img;
});
with lambdas