RAII and smart pointers in C++

A simple (and perhaps overused) example of RAII is a File class. Without RAII, the code might look something like this: File file(“/path/to/file”); // Do stuff with file file.close(); In other words, we must make sure that we close the file once we’ve finished with it. This has two drawbacks – firstly, wherever we use … Read more

Why is it wrong to use std::auto_ptr with standard containers?

The C++ Standard says that an STL element must be “copy-constructible” and “assignable.” In other words, an element must be able to be assigned or copied and the two elements are logically independent. std::auto_ptr does not fulfill this requirement. Take for example this code: class X { }; std::vector<std::auto_ptr<X> > vecX; vecX.push_back(new X); std::auto_ptr<X> pX … Read more

If you shouldn’t throw exceptions in a destructor, how do you handle errors in it?

Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate. #include <iostream> class Bad { public: // Added the noexcept(false) so the code keeps its original meaning. // Post C++11 destructors are by default `noexcept(true)` and // this will (by default) call terminate if an exception … Read more

Does C++ support ‘finally’ blocks? (And what’s this ‘RAII’ I keep hearing about?)

No, C++ does not support ‘finally’ blocks. The reason is that C++ instead supports RAII: “Resource Acquisition Is Initialization” — a poor name† for a really useful concept. The idea is that an object’s destructor is responsible for freeing resources. When the object has automatic storage duration, the object’s destructor will be called when the … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)