How ?
What features to simplify GC are in C ++ 11?
Fundamentals of memory management in C ++ (redefining new / delete for classes for which we want strange):
Garbage collection:
How ?
What features to simplify GC are in C ++ 11?
Fundamentals of memory management in C ++ (redefining new / delete for classes for which we want strange):
Garbage collection:
Please correct the question so that it describes the specific problem with sufficient detail to determine the appropriate answer. Do not ask a few questions at once. See “How to ask a good question?” For clarification. If the question can be reformulated according to the rules set out in the certificate , edit it .
In C ++, there are no and cannot be garbage collection tools. Smart pointers can be used instead. The most versatile of them is shared_ptr . In the constructor of a smart pointer, you must pass a pointer to an already allocated memory, and nowhere else can you use this pointer. When a shared_ptr object is copied, when it is passed as a function parameter, the internal counter of objects that contain the same pointer increases. As soon as the last shared_ptr object is destroyed (goes out of scope), the memory referenced by the internal shared_ptr pointer is automatically freed. Here is an example of use.
void foo() { //Создаём умный указатель, передав ему обычный указатель на массив из 10 целых чисел std::shared_ptr<int> x(new int(10)); //Вызываем функцию, которая использует этот указатель. На стеке создаётся копия объекта x, которая указывает на ту же память bar(x); //Заканчивается область видимости, удаляется x, освобождается память по данному указателю } void bar(std::shared_ptr<int> y) { //Функция работает со своей копией объекта y[5] = 10; //Область видимости закочилась, объект y удаляется, но так как есть ещё один такой же умный указатель, память не освобождается } shared_ptr has a drawback: ring links require manual loop breaks (which forces you to care about the exact moment of the destruction of the data structure). - VladDweak_ptr - yrHeTaTeJlbSource: https://ru.stackoverflow.com/questions/603949/
All Articles