Не очищаются unique_ptr в std::map после выхода из области видимости

Рейтинг: 0Ответов: 0Опубликовано: 12.05.2023

Сам код

#include <memory>
#include <map>
#include <iostream>
#include <random>
#include <chrono>
#include <thread>

struct Session {
    std::unique_ptr<char[]> login;
};

std::random_device rd;
std::mt19937 rng(rd());

int rand( int min, int max ) {
    std::uniform_int_distribution<int> uni( min, max );

    return uni(rng);
}

char randChar() {
    switch( rand( 0, 2 ) ) {
        case 0:
        return (char)rand( (int)'a', (int)'z' );
        case 1:
        return (char)rand( (int)'A', (int)'Z' );
        default:
        return (char)rand( (int)'0', (int)'9' );
    };
}

std::unique_ptr<char[]> randLoginPtr() {

    auto l = rand( 30, 30 );

    auto ptr = std::make_unique<char[]>( l );

    for( int i = 0; i < l-1; i++ ) {
        ptr.get()[i] = randChar();
    }

    return ptr;
};

void test( unsigned int count, std::map<unsigned int, std::unique_ptr<Session>> &sessions ) {
    for( unsigned int i = 0; i < count; i++ ) {
        auto ptr = std::make_unique<Session>();
        ptr->login = randLoginPtr();
        sessions.insert( { i, std::move( ptr ) } );
    }
}

int main() {
    std::cout << "start" << std::endl;

    {
        std::map<unsigned int, std::unique_ptr<Session>> sessions{};
        test( 2'000'000, sessions );
    }

    std::cout << "end" << std::endl;

    std::chrono::milliseconds timespan(100);

    while( true ) {
        std::this_thread::sleep_for(timespan);
    }
}

После цикла остается 275 метров в памяти. Разве не должно автоматически чиститься? Если не должно, то как правильно очистить?

Ответы

Ответов пока нет.