← Samples

Use RAII types

12345678910111213#include <map> #include <memory> #include <string> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; std::map<std::string, int> map = {{"Foo", 10}, {"Bar", 20}}; std::string str = "Some text"; std::unique_ptr<int> ptr1 = std::make_unique<int>(8); std::shared_ptr<int> ptr2 = std::make_shared<int>(16); }

This sample is licensed under the CC0 Public Domain Dedication.

Intent

Avoid manual memory management to improve safety and reduce bugs and memory leaks.

Description

Every object created on lines 8–12 will internally manage some dynamically allocated memory (allocated with the new keyword). They are all, however, implemented such that they deallocate that memory when they are destroyed. This practice is known as RAII.

The user of these classes does not need to perform manual memory management, reducing the risk of memory leaks and other bugs. In fact, the use of new and delete can be avoided entirely by using these RAII types.

Likewise, it is good practice to ensure your own classes also implement the RAII idiom with the rule of five or rule of zero.

Contributors

  • Joseph Mansfield

Last Updated

07 April 2015

Source

Fork this sample on GitHub

Share