Winking Out с полиморфными ресурсами памяти: эффективное высвобождение ресурсов и время жизни объектовC++

Программы на C++. Форум разработчиков
Anonymous
Winking Out с полиморфными ресурсами памяти: эффективное высвобождение ресурсов и время жизни объектов

Сообщение Anonymous »

Я пытаюсь понять технику «подмигивания» на примерах (так как пока не смог найти четкого объяснения). Моя цель — освоить методы, не связанные с UB, которые могут быть эффективными при высвобождении ресурсов.
Вот примеры (частично вдохновленные этим постом).

Код: Выделить всё

#include 
#include 
#include 
#include 

// if defined, the destructor of CallCounter (below) has a side-effect but may not be called, which is UB
//#define ACCEPT_UB

// dummy class
// the question is about the lifetime of objects of this class
class CallCounter final {
public:
std::size_t num = constructor_calls;
CallCounter() { ++constructor_calls; }

~CallCounter() {
#ifdef ACCEPT_UB
++destructor_calls;
#endif
// useless
num = 0;
}

inline static size_t constructor_calls = 0;
inline static size_t destructor_calls = 0;
};

// dynamically allocate a std::pmr::vector into a memory resource and let it go out of scope
auto winkingOut1() {
std::pmr::monotonic_buffer_resource pool;
std::pmr::polymorphic_allocator allocator{&pool};
[[maybe_unused]] auto& winkedOutVector =
*allocator.new_object(5000);
// both the vector and its data are in the memory pool
// wink out memory on exit?
}

// create a local std::pmr::vector and explicitly "kills" its data by releasing its memory resource
auto winkingOut2() {
std::pmr::monotonic_buffer_resource pool;
std::pmr::vector winkedOutVector(&pool);
// only the vector data are in the memory pool
for (std::size_t i = 0; i < 5000; ++i) {
winkedOutVector.emplace_back();
}

// explicitly wink out memory
pool.release();
}

// mere log
auto printResults(std::string_view description) {
std::cout 

Подробнее здесь: [url]https://stackoverflow.com/questions/78667752/winking-out-with-polymorphic-memory-resources-efficient-resource-release-and-ob[/url]

Вернуться в «C++»