C ++静态类& shared_ptr内存泄漏 [英] C++ static classes & shared_ptr memory leaks

查看:206
本文介绍了C ++静态类& shared_ptr内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么下面的代码产生内存泄漏(我使用 boost :: shared_ptr 与静态类实例)。有人可以帮助我吗?

I can't understand why does the following code produce memory leaks (I am using boost::shared_ptr with static class instance). Could someone help me?

#include <crtdbg.h>
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;

#define _CRTDBG_MAP_ALLOC
#define NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)

static struct myclass {
   static shared_ptr<int> ptr;

   myclass() {
      ptr = shared_ptr<int>(NEW int);
   }
} myclass_instance;

shared_ptr<int> myclass::ptr;

int main() {
   _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF    | _CRTDBG_LEAK_CHECK_DF |
                  _CRTDBG_CHECK_ALWAYS_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
   return 0;
}


推荐答案

报告一个假阳性 - 下面的代码说明了共享指针正常工作,至少用g ++

At a guess the CRT is reporting a false positive - the following code illustrates that the shared pointer is working correctly, at least with g++

#include <iostream>
#include "boost/shared_ptr.hpp"
using namespace std;
using namespace boost;

struct R {
    R() {
        cerr << "ctor" << endl;
    }

    ~R() {
        cerr << "dtor" << endl;
    }
};

struct A {
    static shared_ptr<R> ptr;

    A() {
     ptr =  shared_ptr<R>(new R);
    }

};

shared_ptr<R> A::ptr;
static A a;

int main() {
}

ctor
dtor

这篇关于C ++静态类&amp; shared_ptr内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆