std::queue内存释放问题 - Tobycc
220
post-template-default,single,single-post,postid-220,single-format-standard,ajax_fade,page_not_loaded,,qode-theme-ver-13.5,qode-theme-bridge,disabled_footer_bottom,wpb-js-composer js-comp-ver-5.4.5,vc_responsive

std::queue内存释放问题

std::queue内存释放问题

std::queue在pop之后不会释放内存,在执行swap或queue析构时才会释放被pop掉的元素占用的内存
或者定义成shared_ptr的queue可以直接在pop时释放内存

std::queue<std::shared_ptr<double>>

以下面的代码为例:

#include <string>
#include <queue>
#include <glog/logging.h>
int main() {
    std::queue<double> the_queue;
    uint64_t total_size = 5000000000;
    uint64_t step_size = total_size / 10;
    for(uint64_t i = 0; i < total_size; i++)
    {
        double d = 1.0 * (rand() % 1000);
        the_queue.push(d);
        if (the_queue.size() % step_size == 0) {
            LOG(INFO) << "push " << the_queue.size();
            sleep(1);
        }
    }

    LOG(INFO) << "Done pushing\n";

    while(!the_queue.empty())
    {
        the_queue.pop();
        if (the_queue.size() % step_size == 0) {
            LOG(INFO) << "pop " << the_queue.size();
            sleep(1);
        }
    }

    LOG(INFO) << "Done popping\n";
    sleep(10);

    LOG(INFO) << "Start clear\n";
    std::queue<double>().swap(the_queue);
    LOG(INFO) << "Done clear\n";
    sleep(10);
}

queue1
这段时间进程占用的内存从0%增长到20.6%
queue2
这段时间进程占用的内存保持在20.6%
queue3
这段时间进程占用的内存从20.6%降到0%