C++Builder How To Use Smart Pointers For Dynamic C++ Memory Management

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,203
Credits
4,034
How To Use Smart Pointers For Dynamic C++ Memory Management
By Yilmaz Yoru November 4, 2021

In computers, all data and operations during runtime is stored in the memory of our computers, IoTs, or in other microdevices. This memory is generally a RAM (Для просмотра ссылки Войди или Зарегистрируйся) that allows data items to be read or written in almost the same amount of time irrespective of the physical location of data inside the memory.

What is static memory allocation and dynamic memory allocation?​

In programming, generally there are two kinds of memory allocations, Static Memory Allocation, and Dynamic Memory Allocation.

Static Memory Allocation is a memory allocation method that is defined by variable definitions when programming and it has a fixed size, can not be changed during the run-time. These variables are defined variables in our programs like constants, strings, pointers, arrays. When a program is compiled, the compiler allocates part of the memory to store data. This is called Static Memory Allocation or Compile-time Memory. There are limitations in such static memory allocation to use these kinds of variables. Because:

These allocations are done in memory exclusively allocated to a program, we can’t increase the size of static allocations to handle more new elements. Thus, this may result in declaring larger arrays than required which means a waste of memory usage. If we used less data than expected, static memory allocations don’t allow us to reduce array size to save and reclaim memory. It is hard to create advanced dynamic data structures which can be deleted, reallocate variables, linked lists, trees, and other data, which are essential in most real-life programming situations.

Dynamic Memory Allocation is a memory allocation method in which the memory is allocated during the execution of a program (at run-time). Для просмотра ссылки Войди или Зарегистрируйся functions/methods involve the use of pointers and standard library functions. Sometimes we use pointers to point to the address of blocks of memory which are allocated dynamically so we can easily access or operate on those dynamic memory allocations.

The C++ language is a great programming language which builds on the strengths of its ancestor, the C programming language. The C programming language has both Static Memory Allocation and Dynamic Memory Allocation methods.

What are pointers in C and C++?​

Pointers are variables that hold addresses. The asterisk character ‘*’ is used to define pointers; they are used before the variable name. Pointers are some of the strongest aspects of the C & C++ programming languages. They allow you to reach any kind of type including very large sized bitmaps, videos or other data, and so on, without copying the whole data.

For example, we can define a pointer for an integer variable as below,

C++:
int *p;

If you are new to Pointers please read this post below, Для просмотра ссылки Войди или Зарегистрируйся

What are Modern C+ smart pointers?​


Allocating memory and freeing it safely is really hard if you are programming a very big application. In Modern C++, there are smart pointers which helps avoid the mistake of incorrectly freeing the memory addressed by pointers. Smart pointers make it easy to define pointers, they came with C++11. The most used types of C++ smart pointer are unique_ptr, auto_ptr, shared_ptr, weak_ptr.

What is the unique_ptr Smart Pointer?​

std::unique_ptr is a smart pointer that manages and owns another object with a pointer, when the unique_ptr goes out of scope C++ disposes of that object automatically.

The object at that pointer’s referenced memory address is disposed of by the associated ‘deleter’. This happens If the unique_ptr object is destroyed or If the unique_ptr object is assigned another pointer by the operator ‘=’ or by the reset() method. Thus the developer does not need to free or delete this smart pointer. The default deleter uses the ‘delete’ operator which destroys the object and deallocates the memory. A unique_ptr may have no object and that means it is empty.

The std::unique_ptr can be used with a dynamically-allocated array of objects and with the single objects.

What is the syntax for unique_ptr?​

C++:
template < class T, class Deleter = std::default_delete <T> > class unique_ptr;

template < class T, class Deleter > class unique_ptr < T[], Deleter >;
Here is a unique_ptr example used with a struct,
C++:
#include <iostream>
#include <memory>
 
struct st_dat
{
 int X, Y;
};
 
int main()
{
 std::unique_ptr<st_dat> dat( new st_dat );
 
 dat->X = 30;
 dat->Y = 20;
 
 
 std::cout << dat->X << "," << dat->Y << std::endl;
 
 getchar();
 return 0;
}
Here is a C++ Builder VCL Example to unique_ptr used for the TFileStream,
C++:
#include <vcl.h>
#include <memory>
 
struct st_dat
{
 int X, Y;
} dat;
 
int _tmain(int argc, _TCHAR* argv[])
{
 dat.X = 960;
 dat.Y = 540;
 
 std::unique_ptr< TFileStream >fs ( new TFileStream( "D:\\test.dat" , fmCreate |  fmOpenReadWrite) );
 
 if(fs) fs->Write( &dat, sizeof(dat) );
 
 return 0;
}