This might sound like nonsense to you, but RAII is the idea of using an OOP language's encapsulation features to manage your memory and resources so that you don't have to.
C++ has these things called "constructors" and "destructors". They are special functions for classes which are automatically called when the object is created and destroyed. This lets you do any cleanup necessary for the object.
For example:
1 2 3 4 5 6 7 8
|
// without RAII, if we want to dynamically allocate 10 ints, we'd do
// something like this:
int* ar = new int[10]; // allocate the array
ar[0] = 0; // use it
delete[] ar; // clean up when done.
|
If you leave out that last delete[] line, you will leak memory -- as the memory you allocated will not get released.
So if you forget to delete, or if something happens that interrupts your code before you get a chance to delete (like an exception, an early return/break command, or a goto), you will leak memory.
RAII says.. let the destructor do the cleanup so that it is done automatically. This will make it impossible to forget. Also, destructors are called even when code is interrupted, so it will be guaranteed to cleanup, making a leak impossible:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
// An overly simplistic RAII example. DO NOT USE THIS CLASS -- use std::vector
// instead:
class Array // our array class, which will be an RAII container for allocating ints
{
private:
int* data; // our data -- this will point to the actual array
public:
Array( int size ) // our constructor, which takes the number of ints we want to allocate
{
data = new int[size];
}
~Array() // our destructor, which will clean up.
{
delete[] data;
}
int& operator [] (int index) // overloading the [] operator so we can access the array
{ // from outside the class
return data[index];
}
};
// Now that we have this RAII class, we can use it:
Array ar(10); // create an array of 10 ints. This calls the constructor
ar[0] = 0; // use it
// no need to clean up... the destuctor will do it automatically.
|
RAII is smart pointers right |
Smart pointers
use RAII.
and is it important to learn low level concepts |
Not immediately, no. Though you'll want to learn them eventually. If you stick to using smart pointers and container classes, you are very unlikely to leak memory.
So bassically memory management is basically asking for some memmory in your programmes this is called allocation and well thats it is that right |
Kinda.
Allocation is asking for some memory.
Memory management is being responsible with the memory you have already allocated. IE if you allocate memory and never free it, then that is poor memory management. But if you use RAII to ensure you never have any leaks, then that is good memory management.